We help IT Professionals succeed at work.
Get Started

Populating DataGridView from MS SQL Server table

matttsch
matttsch asked
on
1,753 Views
Last Modified: 2013-11-26
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
Comment
Watch Question
Commented:
This problem has been solved!
Unlock 1 Answer and 3 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE