stubborn error when trying to merge a table into a dataset - vb.net

I'm trying to track down a .NET error in my little game here.
Here is the error:
ArgumentNullException: 'table' argument cannot be null
System.DataSet.Merge(DattaTable table)
It's occurring on the line below where it tries to merge a table into an existing dataset.
I'm trying to do as many checks as I think I can to determine if the dataset or table are empty, but it continues to error on the ds.Merge line.
Dim ds As DataSet
'getData = simple function that uses SqlConnection & SqlDataAdapter to get data from my database
ds = utils.getData("Sproc_GetGameEncounters")
Dim MonsterDataSet As DataSet
MonsterDataSet = utils.getData("Sproc_MonsterDataSetFromDB")
If Not MonsterDataSet Is Nothing Then
If MonsterDataSet.Tables("TreasureList") Is Nothing OrElse MonsterDataSet.Tables("TreasureList").Rows.Count = 0 Then
'MonsterDataSet.Tables("TreasureList") is empty
Else
ds.Merge(MonsterDataSet.Tables("TreasureList")) 'line where error occurs
End If
End If
Are there more checks I could add to help fix or at least track down this error?
Thanks!

I had the same problem recently. The problem is the adapter, it not get the names of tables. I have a similar function and I'm happy to share it.
You can set the table name after dataset filled, or with TableMappings (here an answer for TableMappings), but I preferred the first way.
Function to fill the dataset
Private Function sql_fillDataset(sql As String, Optional tablesName As String() = Nothing) As DataSet
dim sql_connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds = New DataSet
Try
sql_connection = New SqlConnection("YOUR_CONNECTION_STRING")
sql_connection.Open()
command = New SqlCommand(sql, sql_connection)
adapter.SelectCommand = command
adapter.Fill(ds)
If Not tablesName Is Nothing AndAlso Not ds Is Nothing AndAlso Not ds.Tables Is Nothing AndAlso ds.Tables.Count = tablesName.Length Then
For i = 0 To ds.Tables.Count - 1
ds.Tables(i).TableName = tablesName(i)
Next
End If
command.Dispose()
adapter.Dispose()
sql_connection.Close()
sql_connection.Dispose()
Return ds
Catch ex As Exception
Return Nothing
End Try
End Function
How to use it
Dim ds As New Dataset
ds = sql_fillDataset("SELECT * FROM TABLE1")
' #### Here is your case, and you haven't the table name
ds.tables(0)
Or
Dim ds As New Dataset
ds = sql_fillDataset("SELECT * FROM TABLE1", New String() {"TABLE1"})
' #### Here is your solution, but the dataset have the name !!
ds.tables("TABLE1")
Or with more than one tables
Dim ds As New Dataset
ds = sql_fillDataset("SELECT * FROM TABLE1; SELECT * FROM TABLE2", New String() {"TABLE1", "TABLE2"})
ds.tables("TABLE1")
ds.tables("TABLE2")
Hope this help you.

Related

Getting DevExpress Chart Series Values From Array VB.NET

I was trying to set DevExpress Chart Series from Data inside SQL Table.
Everything went fine except that the chart takes only the last attribute from the last series.
My code is:
con.Open() 'it opens SQL Connection
For i = 0 To (CheckedListBoxControl1.CheckedItems.Count - 1) 'list from ListBox
Lst.Add(CheckedListBoxControl1.CheckedItems(i).ToString) 'Putting Data in Array List
Dim Strl As String = String.Format("Select * from VPRogressCumulative where fname like '{0}' and lname like '{1}' order by id, no, CAST('1.' + date AS datetime)", ComboBox1.Text, Lst(i))
Dim sqlCom As New SqlCommand(Strl)
sqlCom.Connection = con
Dim myDA As SqlDataAdapter = New SqlDataAdapter(sqlCom)
Dim myDataSet As DataSet = New DataSet()
myDA.Fill(myDataSet, "VPRogressCumulative")
ChartControl1.DataSource = myDataSet
ChartControl1.DataAdapter = myDA
Dim ser As New Series(Lst(i), ViewType.Line)
ChartControl1.Series.Add(ser)
ser.ArgumentDataMember = "VPRogressCumulative.Date"
ser.ValueDataMembers.AddRange(New String() {"VPRogressCumulative.Cumulative"})
Next
con.Close()
I believe my Problem is in:
Dim ser As New Series(Lst(i), ViewType.Line)
ChartControl1.Series.Add(ser)
ser.ArgumentDataMember = "VPRogressCumulative.Date"
ser.ValueDataMembers.AddRange(New String() {"VPRogressCumulative.Cumulative"})
Last two lines are giving the same series new attributes which I wasn't able to resolve the issue.
Your problem is here:
ChartControl1.DataSource = myDataSet
ChartControl1.DataAdapter = myDA
In each iteration of cycle you are creating the new DataSet and it's overrides previous DataSource in your ChartControl1. Your must use Series.DataSource instead of ChartControl.DataSource. Also you can use DataTable instead of DataSet.
Here is example:
'Your code:
'Dim myDataSet As DataSet = New DataSet()
'myDA.Fill(myDataSet, "VPRogressCumulative")
'ChartControl1.DataSource = myDataSet
'ChartControl1.DataAdapter = myDA
'Replace with this:
Dim myDataTable As DataTable = New DataTable("VPRogressCumulative")
myDA.Fill(myDataTable)
Dim ser As New Series(Lst(i), ViewType.Line)
ChartControl1.Series.Add(ser)
'Your code.
'ser.ArgumentDataMember = "VPRogressCumulative.Date"
'ser.ValueDataMembers.AddRange(New String() {"VPRogressCumulative.Cumulative"})
'Replace with this:
ser.DataSource = myDataTable
ser.ArgumentDataMember = "Date"
ser.ValueDataMembers.AddRange(New String() {"Cumulative"})

operator/operand type mismatch when update dbf file

i have a program needs to update data in dbf file. but it keeps appear error 'operator/operand type mismatch'. here is sample code :
Dim con As OleDbConnection = New OleDbConnection("Provider=vfpoledb;Data Source=C:\folder\paytran.dbf;Collating Sequence=machine;")
Try
Dim strSQL As String = "UPDATE paytran.dbf SET workhr = 20 WHERE empno = 102"
Dim cmd As OleDbCommand = New OleDbCommand(strSQL, con)
con.Open()
Dim myDA As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim myDataSet As DataSet = New DataSet()
' Using DataAdapter object fill data from database into DataSet object
myDA.Fill(myDataSet, "MyTable")
' Binding DataSet to DataGridView
DGV.DataSource = myDataSet.Tables("MyTable").DefaultView
con.Close()
con = Nothing
Catch ex As Exception
MessageBox.Show(ex.Message, "Error Select Data")
Finally
If con IsNot Nothing Then
con.Close()
End If
End Try
please help me..
Its your connection string. The connection string should only have to point to the PATH where the data files are located, then all the SQL based commands will by default be able to see any .DBF tables IN that path (or forward if subpaths exists).
Data Source=C:\folder
instead of
Data Source=C:\folder\paytran.dbf
So, now if you have 30 tables in the "C:\folder", you can now query from ALL of them as needed.
You need to explicitly open and close the DBF. Try:
Dim strSQL As String = "Use paytran in 0 shared;UPDATE paytran SET workhr = 20 WHERE empno = 102;use in select('paytran')"

Loop through action

I am new to visual basic, however I need to loop through rows in a data table and use the values to in a test script, the script is as follows -
Public Function TestMain(ByVal args() As Object) As Object
StartApp(URL)
' HTML Browser '
Browser_HtmlBrowser(Document_HomePage(),DEFAULT_FLAGS).Maximize()
Button_AddNewProfilesubmit().Click()
'here is where the rows would be read and the loop would start'
Text_Ctl00MainContentProfileNa().Click(AtPoint(6, 13))
Browser_HtmlBrowser(Document_Http1921685526UserCon(), DEFAULT_FLAGS).InputChars("dataBase_Row_Value")
Table_HtmlTable_1().Click(AtCell( _
AtRow(AtIndex(0)), _
AtColumn(AtIndex(1))))
'here is where the loop would end after all rows had been read'
Return Nothing
End Function
I have an idea to achieve this, first doing a database connection, then create the loop -
Dim pName As String
Dim datas As DataSet
Dim datar As DataRow
Dim oledat As SqlDataAdapter
oledat = New SqlDataAdapter("SELECT COLUMN FROM DATABASE",ConnectionString)
oledat.Fill(datas)
For Each datar In datas.Tables(0).Rows
pName = datar.Item("PROFILENAME")
Text_Ctl00MainContentProfileNa().Click(AtPoint(6, 13))
Browser_HtmlBrowser(Document_Http1921685526UserCon(), DEFAULT_FLAGS).InputChars(pName)
Table_HtmlTable_1().Click(AtCell( _
AtRow(AtIndex(0)), _
AtColumn(AtIndex(1))))
Next
However this is breaking, even though there are no errors in Visual Studio, there is only the warning that datas is used before it is assigned the values. Where am I going wrong?
I believe you must initialize a new dataset before working with it. Example:
Dim ds As DataSet = New DataSet()
Dim connection As OleDb.OleDbConnection
Dim command As OleDb.OleDbCommand
Dim adapter As New OleDb.OleDbDataAdapter
Dim connString As String = "my Connection string stuff;"
connection = New OleDb.OleDbConnection(connString)
Try
'open the connection
If connection.State = ConnectionState.Open Then
Else
connection.Open()
End If
'fill each data table
command = New OleDb.OleDbCommand(selectOne, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "someTableName")
Catch ex As OleDb.OleDbException
'error, do something
Finally
'close everything down
adapter.Dispose()
If (Not command Is Nothing) Then
command.Dispose()
End If
connection.Close()
End Try
This example uses OLEDB but should be comparable to what you are doing. Once you fill it, you should be able to iterate over the tables. But, first, check to make sure you have a dataset created first:
If (ds IsNot Nothing) Then
'do for statement here
End If
If this does not work, let me know.

Saving record with dataset

I want to save a record in the database using a dataset, but my data is not committing into my database.
My code can be viewed below:
Dim mydataset1 As New MyDataSet
Dim row As DataRow = mydataset1.Tables("testtable").NewRow()
With row
.Item("name") = "Segun Omotayo"
.Item("address") = "Abuja"
End With
mydataset1.Tables("testtable").Rows.Add(row)
Any help will be appreciated
A DataSet/DataTable is a offline/in-memory representation of your database. If you want to update the database, you need to use a DataAdapter.
For example (assuming you're using MS-Sql-Server):
Public Function UpdateDataSet(dataSet As DataSet) As Int32
Using con = New SqlConnection(My.Settings.SqlConnection)
Dim sql = "INSERT INTO TUser(Name,Address)VALUES(#Name,#Address)"
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.Add(New SqlParameter("#Name", SqlDbType.VarChar))
cmd.Parameters.Add(New SqlParameter("#Address", SqlDbType.VarChar))
Using da = New SqlDataAdapter()
da.InsertCommand = cmd
con.Open()
Dim rowCount = da.Update(dataSet)
Return rowCount
End Using
End Using
End Using
End Function
I could be rusty here since its a long time since I wrote any VB.NET or used data adapters/datasets/datatables but I think if you decide to take that route you would need code like this:
Dim connection As New SqlConnection("#####YourConnectionString#####")
connection.Open()
Dim adapter As New SqlDataAdapter("SELECT * FROM testtable", connection)
' For the line below to work, you must have a primary key field in "testtable"
Dim builder As New SqlCommandBuilder(adapter)
Dim testtable As New DataTable("testtable")
adapter.Fill(testtable)
Dim row As DataRow = testtable.NewRow()
With row
.Item("name") = "Segun Omotayo"
.Item("address") = "Abuja"
End With
testtable.Rows.Add(row)
adapter.Update(testtable)
connection.Close()

Windows Forms App: System.NullReferenceException Error

Good day,
I have been trying to figure out the source of error in my application. What this function (GetConcentrations()) is to display data from my database onto a DataGridView. The function is called in the PageLoad but works fine but when I call it in another Sub, I get this error.
Could anyone help me? I already tried different ways.
Thanks!
Here is the code:
Private Sub GetConcentrations()
Dim conString As String = ConfigurationManager.ConnectionStrings("dbAsthmaConnectionString").ConnectionString
Me.dataAdapter = New SqlDataAdapter("Select * from tblConcentrations", conString)
'Dim adapter As New SqlDataAdapter("Select * from tblConcentrations", conString)
Dim dataset As New Data.DataSet
Try
Dim commandBuilder As New SqlCommandBuilder(Me.dataAdapter)
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
'Dim datasetgetconcentrations = New DataSet
Me.dataAdapter.Fill(dataset)
Me.bindingSource1.DataSource = table
DataGridView3.AutoResizeColumns(DataGridViewAutoSizeColumnMode.AllCellsExceptHeader)
DataGridView3.DataSource = dataset.Tables(0)
dataset.Dispose()
Catch ex As Exception
MsgBox("Failed to display the concentration table (GetConcentrations)!", MsgBoxStyle.Information)
End Try
'Dim ConcentrationValue As Double = DataGridView2.Rows.Contains
'TextBoxCurrentConcentration.Text = txtMessage.Text
End Sub
I don't understand why you call the Fill method two times.
Once to fill a DataTable and one again to fill a DataSet. Only the one for the dataset is really needed.
Could you try if this changes something in your problem?
Dim ds as New DataSet
ds.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(ds)
DataGridView3.AutoResizeColumns(DataGridViewAutoSizeColumnMode.AllCellsExceptHeader)
DataGridView3.DataSource = ds.Tables(0)
Also, don't dispose your dataset on exiting, you are still using it.
In this case it's better to let the Garbage Collection handle this task.