I'm trying to execute some SQL queries that takes long time and returns a lot of rows, and that's why i use SqlDataReader for returning the rows.
I execute the query in a separate thread, so the UI would be usable while the rows are returned.
I also have a datatable, which i'm filling with the SqlDataReader, and the DataTable is bound to a BindingSource, and the BindingSource is bound to the DataGridView.
The problem is that the DataGridView seems to be unable to bind the columns of the DataTable to the Columns in the DataGridView, and all cells in the grid shows blank. Even with AutoGenerateColumns=true, the data is not shown!
The below is an example code quite similar to my problem:
public partial class Form2 : Form
{
BindingSource binding;
DataTable dt = new DataTable();
DataGridView dgv;
public Form2()
{
InitializeComponent();
binding = new BindingSource();
binding.DataSource = dt;
dgv = new DataGridView();
dgv.Columns.Add("Column1", "Column1");
dgv.Columns[0].DataPropertyName = "Column1";
dgv.AutoGenerateColumns = false;
dgv.DataSource = binding;
dgv.Click += new EventHandler(dgv_Click);
this.Controls.Add(dgv);
dostuff(); // ON FIRST TRY 5 ROWS SHOWN
}
void dgv_Click(object sender, EventArgs e)
{
dostuff(); // ON SECOND RUN EVERYTHING IS CLEARED!
}
void dostuff()
{
dgv.DataSource = null;
dt.Rows.Clear();
dt.Columns.Clear();
dgv.DataSource = binding;
BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.RunWorkerAsync();
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
dt.Rows.Clear();
dt.Columns.Clear();
dt.Columns.Add("Column1");
for (int i = 0; i < 5; i++)
{
DataRow r = dt.NewRow();
r[0] = i;
dt.Rows.Add(r);
}
}
}