Avatar of matttsch
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("Data Source=foo;Initial Catalog=bar;User ID=baz;Password=quax")
                Dim adapter As New SqlClient.SqlDataAdapter(sql, 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
.NET ProgrammingEditors IDEs

Avatar of undefined
Last Comment
RobertRFreeman

8/22/2022 - Mon
Pratima

after this

data.DataSource = ds

add
data.Databind()
ASKER CERTIFIED SOLUTION
dragy

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
RobertRFreeman

The wizard creates a datasource object.  I'd recommend changing the properties on the DataSource control rather than on the DataGridView.
Your help has saved me hundreds of hours of internet surfing.
fblack61