Search code examples
c#sqlsql-server-2008datatablesqldataadapter

SQL C# interactions not working


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?


Solution

  • 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.