user2023203 user2023203 - 1 month ago 21
C# Question

Populate a datagridview with sql query results

I'm trying to present query results, but I keep getting a blank data grid.
It's like the data itself is not visible

Here is my code:

private void Employee_Report_Load(object sender, EventArgs e)
{
string select = "SELECT * FROM tblEmployee";
Connection c = new Connection();
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, c.con); //c.con is the connection string
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;

dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}


What's wrong with this code?

Answer

Here's your code fixed up. Next forget bindingsource

 string select = "SELECT * FROM tblEmployee";
 Connection c = new Connection();
 SqlDataAdapter dataAdapter = new SqlDataAdapter(select, c.con); //c.con is the connection string

 SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
 DataSet ds = new DataSet();
 dataAdapter.Fill(ds);
 dataGridView1.ReadOnly = true; 
 dataGridView.DataSource = ds.tables[0];