VB.Net Parameter count mismatch - vb.net

I'm writing a function that convert an Array List into a Data Table, and I'm getting an error "Parameter count mismatch".
I've been looking and googling the issue but couldn't found anything that could help me resolve my issue.
```
'Function that convert ArrayList to DataTable
Public Function ConvertArrayListToDataTable(ByVal MyAList As ArrayList) As DataTable
Dim dt As New DataTable()
For i As Integer = 0 To MyAList.Count - 1
'create a Generic Object
Dim values As Object = MyAList.Item(i)
Dim properties() As PropertyInfo =
values.GetType().GetProperties()
'Loop through each property, and add it as a column to the datatable
For Each prop As PropertyInfo In properties
Try
Dim dc As DataColumn = New DataColumn(prop.Name)
'Add the column definition to the datatable
dc.DataType = prop.PropertyType
dt.Columns.Add(dc)
Catch ex As Exception
MessageBox.Show(" Can't add column" & ex.Message)
End Try
Next
'for each object in the list, loop through and add
'the data to the database
For Each o As Object In MyAList
Try
'create new row
Dim row As DataRow = dt.NewRow()
Dim pf() As PropertyInfo = o.GetType().GetProperties()
For Each item As PropertyInfo In pf
row(item.Name) = item.GetValue(o, Nothing)
Next
dt.Rows.Add(row)
Catch ex As Exception
MessageBox.Show(" Conversionerror" & ex.Message)
End Try
Next
Next
Return dt
End Function
```
I see the code get the Table and the column count as well, but cannot write value. it failed on getvalue.
The function suppose return a datatable containing retrieved data and populate datagrid
For Each prop As PropertyInfo In properties
Try
Dim dc As DataColumn = New DataColumn(prop.Name)
dc.DataType = prop.PropertyType
dt.Columns.Add(dc)
Catch ex As Exception
MessageBox.Show(" Can't add column" & ex.Message)
End Try
Next

If you are filling a DataTable from a database just let the DataTable figure out the datatype. ArrayList is not used in new code. You can make a class or structure and then use List(Of T) or if absolutely necessary List(Of Object). Test just the plain old DataTable.
Private Sub FillDataGridView()
Dim dt = New DataTable()
Using cn As New SqlConnection(My.Settings.CoffeeConnection)
Using cmd As New SqlCommand("Select * From Coffees;", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
For Each col As DataColumn In dt.Columns
Debug.Print(col.DataType.Name)
Next
DataGridView1.DataSource = dt
End Sub

Thank you Mary. It was a great experience. I was challenging myself to see how I can fill the Datagrid from Arraylist to Datatable. I finally follow your advice and review my Function as below:
Public Function FillDataGridView(SQLStatement As String) As DataTable
'create an DataTable to hold the results
Dim dt As New DataTable()
Try
Using con As New SqlConnection(ConnectionString)
con.Open()
Using cmd As New SqlCommand(SQLStatement, con)
'Get the reader
Using Reader = cmd.ExecuteReader()
dt.Load(Reader)
End Using
End Using
End Using
For Each col As DataColumn In dt.Columns
Debug.Print(col.DataType.Name)
Next
Catch ex As Exception
Console.WriteLine("SQL retrieve row:" & ex.Message & Err.Number)
Finally
Call CloseConn()
End Try
Return dt
End Function

Related

VB.NET How to correctly loop through a result set

I have looked at many different code snippets on this site looking that would show me how to do something that should be fairly simple once I have the knowledge.
I want to query a database table for an array of values and then populate a combobox with those results.
Here is what I have so far:
Public Sub getMachines()
Try
Dim SQL As String = "SELECT MachineName from machine"
Form1.machineName.DisplayMember = "Text"
Dim tb As New DataTable
tb.Columns.Add("Text", GetType(String))
Using cn As New MySqlConnection(ConnectionString)
Using cmd As New MySqlCommand(SQL, cn)
For Each cmd As String In cmd
'I want to add each value found in the database to "tb.Rows.Add"
'tb.Rows.Add(???)
Next
Form1.machineName.DataSource = tb
cn.Open()
cmd.ExecuteNonQuery()
End Using
cn.Close()
End Using
Catch ex As MySqlException
MsgBox(ex.Message)
End Try
End Sub
I proceeded much like you did. I used the Load method of the DataTable. It is not necessary to set the column name and type. The name of the column is taken from the Select statement and the datatype is inferred by ADO.net from the first few records.
Luckily a DataTable can be an Enumerable using the .AsEnumnerable method. Then we can use Linq to get all the values from the MachineName column. Calling .ToArray causes the Linq to execute. If you hold your cursor over names on this line you will see that the datatype is String(). Just what we need to fill a combo box.
Code for a class called DataAccess
Private ConnectionString As String = "Your Connection String"
Public Function GetMachineNames() As String()
Dim tb As New DataTable
Dim SQL As String = "SELECT MachineName from machine;"
Using cn As New MySqlConnection(ConnectionString)
Using cmd As New MySqlCommand(SQL, cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Dim names = dt.AsEnumerable().Select(Function(x) x.Field(Of String)("MachineName")).ToArray()
Return names
End Function
In the form load you combo box like this.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim DatAcc As New DataAccess()
Dim arr = DatAcc.GetMachineNames()
machineName.DataSource = arr
End Sub
If you just want the MachineName to be displayed in the ComboBox, then just use that as the DisplayMember; don't bother creating another column called Text.
Public Sub getMachines()
Try
Dim cmd As String = "SELECT MachineName from machine"
Dim ds As New DataSet()
Using con As New MySqlConnection(ConnectionString)
Using da As New MySqlDataAdapter(cmd, con)
da.Fill(ds)
With Form1.machineName
.DisplayMember = "MachineName"
.ValueMember = "MachineName"
.DataSource = ds
End With
End Using
End Using
Catch ex As MySqlException
MsgBox(ex.Message)
End Try
End Sub
I'll show a few examples, including using parameters, since that is important.
First up, a quick translation to run the existing query and loop through the results:
Public Sub getMachines()
Try
Dim SQL As String = "SELECT MachineName from machine"
Using cn As New MySqlConnection(ConnectionString), _
cmd As New MySqlCommand(SQL, cn)
cn.Open()
Using rdr As MySqlDatareader = cmd.ExecuteReader
While rdr.Read()
Form1.machineName.Items.Add(rdr("MachineName"))
End While
End Using
End Using
Catch ex As MySqlException
MsgBox(ex.Message)
End Try
End Sub
But better practice for a method like this is to isolate data access for the UI. This method should return results to the caller, which can decide what do with them. So I'll show two methods: one to get the data, and the other to loop through it and set up the combobox:
Private Function GetMachines() As DataTable
'No try/catch needed here. Handle it in the UI level, instead
Dim SQL As String = "SELECT MachineName from machine"
Dim result As New DataTable
Using cn As New MySqlConnection(ConnectionString), _
cmd As New MySqlCommand(SQL, cn),
da As New MySqlDataAdapter(cmd)
da.Fill(result)
End Using
Return result
End Function
Public Sub LoadMachines()
Try
For Each item As DataRow in getMachines().Rows
Form1.machineName.Items.Add(item("MachineName"))
Next
Catch ex As MySqlException
MsgBox(ex.Message)
End Try
End Sub
Or, we can use DataBinding:
Private Function GetMachines() As DataTable
Dim SQL As String = "SELECT MachineName from machine"
Dim result As New DataTable
Using cn As New MySqlConnection(ConnectionString), _
cmd As New MySqlCommand(SQL, cn),
da As New MySqlDataAdapter(cmd)
da.Fill(result)
End Using
Return result
End Function
Public Sub LoadMachines()
Try
Form1.machineName.DisplayMember = "FirstName";
Form1.machineName.ValueMember = "City"
Form1.machineName.DataSource = GetMachines()
Catch ex As MySqlException
MsgBox(ex.Message)
End Try
End Sub
If you ever want to use a filter, you might do this (notice the overloading):
Private Function GetMachines(ByVal machineFilter As String) As DataTable
Dim SQL As String = "SELECT MachineName from machine WHERE MachineName LIKE #Filter"
Dim result As New DataTable
Using cn As New MySqlConnection(ConnectionString), _
cmd As New MySqlCommand(SQL, cn),
da As New MySqlDataAdapter(cmd)
'Match the MySqlDbType to your actual database column type and length
cmd.Parameters.Add("#Filter", MySqlDbType.VarString, 30).Value = machineFilter
da.Fill(result)
End Using
Return result
End Function
Private Function GetMachines(ByVal machineFilter As String) As DataTable
Return GetMachines("%")
End Function
Query parameters like that are very important, and if you were doing string concatenation to accomplish this kind of thing on your old platform, you were doing very bad things there, too.
Finally, let's get fancy. A lot of the time, you really don't want to load an entire result set into RAM, as is done with a DataTable. That can be bad. Instead, you'd like be able to stream results into memory and only work with one at a time, minimizing RAM use. In these cases, you get to play with a DataReader... but returning a DataReader object from within a Using block (which is important) doesn't work that well. To get around this, we can use functional programming concepts and advanced language features:
Private Iterator Function GetMachines(ByVal machineFilter As String) As IEnumerable(Of String)
Dim SQL As String = "SELECT MachineName from machine WHERE MachineName LIKE #Filter"
Using cn As New MySqlConnection(ConnectionString), _
cmd As New MySqlCommand(SQL, cn)
'Match the MySqlDbType to your actual database column type and length
cmd.Parameters.Add("#Filter", MySqlDbType.VarString, 30).Value = machineFilter
cn.Open()
Using rdr As MySqlDatareader = cmd.ExecuteReader
While rdr.Read()
Dim result As String = rdr("MachineName")
Yield Return result
End While
End Using
End Using
Return result
End Function
Private Function GetMachines() As IEnumerable(Of String)
Return GetMachines("%")
End Function

Am I loading datatable twice & update row item with boolean value

I call the following function in a module
Public Function GetExcelData(ByVal ExcelFile As String) As System.Data.DataTable
Then I have the following code
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
gblCompName = openFileDialog1.FileName
End If
Dim reader As New DataTableReader(GetExcelData(gblCompName))
Dim table As New DataTable
table.Load(reader)
table.Columns.Add("Single", GetType(Boolean), False)
table.Columns.Add("CouplesInFinal", GetType(Int32))
table.Columns.Add("EvtNum", GetType(String))
table.Columns.Add("EvtStruct", GetType(Int32))
table.Columns.Add("EvtCplID", GetType(Int32))
table.Columns.Add("CouplesInClass", GetType(Int32))
table.Columns.Add("Valid", GetType(Boolean), True)
Dim result() As DataRow = table.Select("[class]" Like "Single")
For Each row In result
If row.Item("Class") Like "Single" Then
table.Rows(0)("Single") = True
End If
Next
DataGridView1.DataSource = table
My logic tells me I'm loading the table twice & the data row field "Single" is boolean which I'm trying to update to True if string field "class" is like "Single"
I realize it's 2 questions in one but it seems to load quite slowly & it's all one form procedure. Any advice on this will be very welcome thanks
Dim reader As New DataTableReader(GetExcelData(gblCompName))
Dim table As New DataTable
Without seeing GetExcelData it is hard to say if you are filling twice. If this function returns a populated DataTable then
Dim table as DataTable = GetExcelData(gblCompName)
and delete the table.Load and the DataReader.
Here is my version of updating a DataTable against my sample database.
Private Sub TestDataTableUpdate()
Try
Using cmd As New SqlCommand("Select * From Coffees", CoffeeCn)
Dim dt As New DataTable
CoffeeCn.Open()
Using dr As SqlDataReader = cmd.ExecuteReader
dt.Load(dr)
End Using
CoffeeCn.Close()
For index As Integer = 0 To dt.Rows.Count - 1
If dt.Rows(index)("Name").ToString = "Cinnamon Stick" Then
dt.Rows(index)("Roast") = "N/A"
End If
Next
'The above does not update the database
Dim da As New SqlDataAdapter(cmd) 'provides the connection and Select command
Dim sqlCB As New SqlCommandBuilder(da) 'Associates the DataAdapter to the command builder
sqlCB.GetUpdateCommand() 'Retrieve the update command for the DataAdapter
'Note: the DataAdapter opens and closes the connection for you
da.Update(dt) 'This updates the database by finding the changed rows in the datatable
'and running the Update command
dt.AcceptChanges() 'Reset the row status to unchanged
DataGridView1.DataSource = dt
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
CoffeeCn.Close()
End Try
End Sub
PS. I am self-taught also.
The table update method that I got to work is
Dim i As Integer = 0
For i = 0 To table.Rows.Count - 1
If table.Rows(i)("Class") Like "*Single*" Then
table.Rows(i)("Single") = True
End If
Next
I took out the ",False" on this line table.Columns.Add("Single", GetType(Boolean)

How do I create a dataset in VB.NET from this code?

I currently have the following code in my project which populates a DataGridView object with the results of an SQL query.
Sub PerformQuery(ByVal SQLText As String)
Dim DbConnection As New OleDb.OleDbConnection(createConnectionString)
Dim SQLQuery As String = SQLText
Dim Adapter As New OleDb.OleDbDataAdapter(SQLQuery, DbConnection)
Try
Using Table As New DataTable
Adapter.Fill(Table)
Table.Locale = Globalization.CultureInfo.InvariantCulture
DbConnection.Close()
DataGridView1.DataSource = Table
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Elsewhere in my project I can create a DataSet object using the code
Dim ds As New DataSet
And then extract data from it using code like:
MaxRows = ds.Tables("Dataset_Users").Rows.Count
Rather than populating a DataGridView, how can I use the PerformQuery code to create a dataset?
Thank you in advance for your help.
I think you are after the following:
Try
Dim ds As New DataSet
Using Table As New DataTable
Adapter.Fill(Table)
Table.Locale = Globalization.CultureInfo.InvariantCulture
DbConnection.Close()
DataGridView1.DataSource = Table
ds.Table.Add(Table)
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
Or as in your example you was after the Number of rows in the dataset you can do the same with the DataTable, For Example:
Try
Dim MaxRows As Integer
Using Table As New DataTable
Adapter.Fill(Table)
Table.Locale = Globalization.CultureInfo.InvariantCulture
DbConnection.Close()
DataGridView1.DataSource = Table
'' Getting the number of rows in the DataTable
MaxRows = Table.Rows.Count
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
Think in a more functional style. Return the table instead of setting to grid. While we're here, let's update the method so you don't have to write queries anymore that leave you wide open to sql injection attacks:
Function PerformQuery(ByVal SQLText As String, ByVal ParamArray Parameters() As OleDbParameter) As DataTable
Dim result As New DataTable()
Using cn As New OleDb.OleDbConnection(createConnectionString), _
cmd As New OleDb.OleDbCommand(SQLText, cn), _
Adapter As New OleDb.OleDbDataAdapter(cmd, cn)
If Parameters IsNot Nothing AndAlso Parameters.Length > 0 Then
cmd.Parameters.AddRange(Parameters)
End If
Adapter.Fill(result)
End Using
Return Result
End Function
Note that I also removed the error handling and locale code. You still need to do that stuff, but when you want to just return a datatable instead of interact directly with the user interface in a method you have effectively moved your code to a lower level of abstraction. When you do that, you probably don't want to deal with the error handling at this lower level any more; instead let the exceptions bubble up where you can handle them closer to the user interface.
Now you call the updated method like this:
Dim sql As String = "SELECT * FROM Customers WHERE CustomerID = ?"
Dim CustID As New OleDb.OleDbParameter("CustomerId", OleDbType.Integer)
CustID.Value = 123456
Try
DataGridView1.DataSource = PerformQuery(sql, CustID)
Catch Ex As Excpetion
MsgBox(Ex.Message)
End Try

Displaying SQLite Data In DataGridView VB.net

I am using sqlite database and using vb.net i am trying to print some rows in datagridview. I use the following code:
Public Sub LoadUsername()
Dim ConnectionString As String = "Data Source=info.sqlite"
Dim nSQL As String = "SELECT Name From employee"
Dim dt As DataTable = Nothing
Dim ds As New DataSet
Try
Using con As New SQLiteConnection(ConnectionString)
Using cmd As New SQLiteCommand(nSQL, con)
con.Open()
Using da As New SQLiteDataAdapter(cmd)
Console.WriteLine(da)
da.Fill(ds)
dt = ds.Tables(0)
End Using
End Using
End Using
ListBox1.ValueMember = "Name"
ListBox1.DisplayMember = "FullName"
ListBox1.DataSource = dt
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
but when i execute or compile this program, it shows me System.Data.DataRowView in the field where name should be. please check the image. Thanks!
There is no FullName column in your datatable yet that's what you're trying to bind the display to. Change the DisplayMember to Name as it should work correctly.
System.Data.DataRow is just the default ToString implementation as it cant find your fullname property.

How to solve this: Conversion from type DBNull to type string is not valid

I think this is were I think the error is showing when I close the crystal report after creating a report.
Private Sub Populate(id As Integer, perdate As Date, controlnum As String, establishmentname As String, fname As String, mname As String, lname As String, address As String, pertype As String, ornum As String, amntpd As String, datepd As Date)
Dim row As String() = New String() {id, perdate, controlnum, establishmentname, fname, mname, lname, address, pertype, ornum, amntpd, datepd}
DataGridView1.Rows.Add(row)
End Sub
This is where the code for retrieving data from my database(MySql database) to datagrid view
Private Sub retrieve()
DataGridView1.Rows.Clear()
sql = "SELECT * FROM tblfsesmis"
Try
Using con
con.Open()
cmd = New MySqlCommand(sql, con)
adapter = New MySqlDataAdapter(cmd)
adapter.Fill(dt)
For Each row In dt.Rows
'It's in your Populate function that you want to check the DBNull values
Populate(row(0), row(1), row(2), row(3), row(4), row(5), row(6), row(7), row(8), row(9), row(10), row(11))
Next
dt.Rows.Clear()
DataGridView1.Refresh()
End Using 'con Object will be disposed automatically
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Can you help me in how to solve this? please ! thank you
If your application doesn't support null values for a field then modify your query so that null values cant appear.
So instead of: SELECT * FROM tblfsesmis
Use SELECT Id, PerDate, IsNull(ControlNum, '') .... FROM tblfsesmis.
IsNull will replace null values with a default that you have chosen.
Alternatively you can fix this in code with something like
Dim result = If(Convert.IsDBNull(val), "", val) on each field which could be null.
However as pointed out in the comment you don't appear to need these values to be cast to strings anyway. So just assign the datatable directly to the datasource.
Private Sub retrieve()
sql = "SELECT * FROM tblfsesmis"
Try
Using con
con.Open()
cmd = New MySqlCommand(sql, con)
adapter = New MySqlDataAdapter(cmd)
adapter.Fill(dt)
DataGridView1.DataSource = dt
End Using 'con Object will be disposed automatically
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Use DataRow.Field(Of T) extension method.
With DataRow.Field(Of String)(columnIndex) if value is DbNull then Nothing/null will be returned.
Populate(row.Field(Of Integer)(0), row.Field(Of String)(1))
If column of type Integer can be a NULL too, then use Nullable with GetValueOrDefault method
Populate(row.Field(Of Integer?)(0).GetValueOrDefault(), row.Field(Of String)(1))
But as #F0r3v3r-A-N00b suggested - you can use DataTable as datasource for DataGridView.
Private Sub retrieve()
Dim sql As String = "SELECT * FROM tblfsesmis"
Try
Using con As New MySqlConnection(yourConnectionString)
con.Open()
Using cmd As New MySqlCommand(sql, con)
Dim adapter As New MySqlDataAdapter(cmd)
Dim dt As New DataTable()
adapter.Fill(dt)
DataGridView1.DataSource = dt
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
In this way DataGridView will be updated automatically. Just check that DataGridView.AutoGenerateColumns = true(it is true by default)