matttsch
asked on
Populating DataGridView from MS SQL Server table
I am writing my first VB.Net App and I am trying to populate a DataGridView with the contents of MS SQL Server table. However, we I run my code, I see the DataGridView being displayed, but it is empty: no column names, no data, does even show empty rows, just a empty gray box. No errors are displayed.
I am able to successfully populate a DataGridView that I created by dragging data sources from the "Data Sources" window onto a DataGridView. I use the same connection string in my code that was generated by the Data Sources Wizard. I want to be able to programmatically create DataGridViews instead of using the Wizard because my App will have 30 near-identical tables that I would like to create in a for loop.
Below is my code:
data = New DataGridView
Dim sql As String = "select * from tmp_sr"
Dim ds As New DataSet
Using connection As New SqlClient.SqlConnection("D ata Source=foo;Initial Catalog=bar;User ID=baz;Password=quax")
Dim adapter As New SqlClient.SqlDataAdapter(s ql, connection)
connection.Open()
adapter.Fill(ds)
End Using
data.DataSource = ds
Me.Controls.Add(data)
I am using MS Visual Studio 2005 and SQL Server 2005
I am able to successfully populate a DataGridView that I created by dragging data sources from the "Data Sources" window onto a DataGridView. I use the same connection string in my code that was generated by the Data Sources Wizard. I want to be able to programmatically create DataGridViews instead of using the Wizard because my App will have 30 near-identical tables that I would like to create in a for loop.
Below is my code:
data = New DataGridView
Dim sql As String = "select * from tmp_sr"
Dim ds As New DataSet
Using connection As New SqlClient.SqlConnection("D
Dim adapter As New SqlClient.SqlDataAdapter(s
connection.Open()
adapter.Fill(ds)
End Using
data.DataSource = ds
Me.Controls.Add(data)
I am using MS Visual Studio 2005 and SQL Server 2005
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
The wizard creates a datasource object. I'd recommend changing the properties on the DataSource control rather than on the DataGridView.
data.DataSource = ds
add
data.Databind()