Populating a DataGridView from SQLReader

I am a little stuck on some code that I am writing

The scheme is that I am reading some data from an SQL database and want to display it in a DataGridView in a form. I have confirmed that the data is returned from the database, but I am not sure why this is not displayed. I followed several tutorials from the Internet, but havenโ€™t worked yet.

here is my code

Private Sub PopulateGrid() Dim Con As New SqlClient.SqlConnection Dim strCon As String = CropTrackMod.strConn Dim strCommand As String = "select * from customer" Try Con.ConnectionString = strCon Dim Cm As New SqlClient.SqlCommand(strCommand, Con) Con.Open() Dim reader As SqlClient.SqlDataReader = Cm.ExecuteReader() 'test to confirm data received reader.Read() MsgBox(reader.Item("ContactName")) DataGridView1.AutoGenerateColumns = True DataGridView1.DataSource = reader DataGridView1.Refresh() Catch ex As Exception MessageBox.Show(ex.Message, "Error") Finally If Con.State = ConnectionState.Open Then Con.Close() End If End Try End Sub 

I also tried implementing a datatable, but getting a data type conversion error any help would be appreciated

thanks guys

+6
source share
1 answer

You cannot bind datareader directly to datagridview in WinForms. Instead, you can load data with your reader and assign data related to the DataGridView data source.

 Dim dt = new DataTable() dt.Load(reader) DataGridView1.AutoGenerateColumns = True DataGridView1.DataSource = dt DataGridView1.Refresh() 
+12
source

Source: https://habr.com/ru/post/951406/


All Articles