2

I'm trying to ping my SQL server with a query for information, and then pass that information into a DataGridView. Though it won't be shown in my code, I do open my DBConnection first and then close it afterwards. My code is shown below:

            using (SqlDataAdapter newDA = new SqlDataAdapter(query, DBConnection))
        {
            DataTable Table = new DataTable();
            newDA.Fill(Table);

            dgvOutput.DataSource = Table;
        }

I know that query and DBConnection are both functioning because they work in a similar part of the program, but for some reason, newDA doesn't seem to be getting any data from the database here. When I copy the query's value directly into Microsoft SQL Server Management Studio and run it, it gets the data just fine. Any suggestions?

Kulahan
  • 512
  • 1
  • 9
  • 23
  • Could you show the query text? – Steve Jul 10 '12 at 21:03
  • "I do open my DBConnection first and then close it afterwards." SqlTableAdapters handle the closing and opening of the connection... http://stackoverflow.com/a/956469/1449777 – Tom Jul 10 '12 at 21:08
  • There is nothing wrong with the code that you have posted. The problem is either in the way you are displaying the datagridview, or in your query. I would suggest that you set a break point after newDA.Fill(Table); and check to see if the table is being populated with data. – Tom Jul 10 '12 at 21:11

2 Answers2

3
string connectionString = YOUR_NAME_SPACE.Properties.Settings.Default.CONNECTION_STRING;
            SqlConnection con = new SqlConnection(connectionString);
            DataTable DT = new DataTable();
            con.Open();

            SqlDataAdapter DA = new SqlDataAdapter(YOUR_QUERYQUERY, connectionString);
            DA.Fill(DT);
            con.Close();
            return DT;

Now After putting this code. in you project with little changes. I hopw you'll get what to change.

You will have the DataTable. this contain all the content. you can easily put the content to the datagrid view. It's easy.

Khizar Ali
  • 486
  • 2
  • 12
  • 26
0

Well, after staring at my screen for a few hours more, I realized what I was missing:

dgvOutput.AutoGenerateColumns = true;

Once I entered this, everything worked just fine.

Kulahan
  • 512
  • 1
  • 9
  • 23