Click here to Skip to main content
15,883,883 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
In the following code, the DataSource 'ds' has data but the DataGridView doesnt show anything except blank columns. Using debugger, at line dataGridView.visible=true it shows as false.

How to bind database columns to DataGridView columns?
C#
List<string> adds = new List<string>();
SqlDataAdapter da = new SqlDataAdapter("seLECT YEAR(startdt) AS [Year],MONTH(startdt) AS [Month], DAY(startdt) as [day],cast(startdt as datetime) as [datetime], COUNT(*),ipaddress from visit Group By YEAR(startdt), MONTH(startdt),day(startdt),startdt,ipaddress", con);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds, "normalpackage");

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
    adds.Add(ds.Tables[0].Rows[i].ItemArray[0].ToString());
}
dataGridView1.DataSource = ds;
bindingSource1.DataSource = ds;
dataGridView1.Visible = true;
Posted
v2
Comments
While debugging see if the DataSet ds is having rows or not by hovering on it.

1 solution

You must use DataBind(), after assigning datasource to gridview. See the code below,

C#
List<string> adds = new List<string>();
SqlDataAdapter da = new SqlDataAdapter("seLECT YEAR(startdt) AS [Year],MONTH(startdt) AS [Month], DAY(startdt) as [day],cast(startdt as datetime) as [datetime], COUNT(*),ipaddress from visit Group By YEAR(startdt), MONTH(startdt),day(startdt),startdt,ipaddress", con);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds, "normalpackage");
 
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
    adds.Add(ds.Tables[0].Rows[i].ItemArray[0].ToString());
}
dataGridView1.DataSource = ds;
dataGridView1.DataBind();
bindingSource1.DataSource = ds;
dataGridView1.Visible = true;</string></string>

-KR
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900