Reputation: 572
I have a datagridview. When I programmatically add a new row, it should appear immediately on datagridview, instead of waiting to finish all the rows I have.
I was working with the solution below
...
adapter.Fill(ds);
foreach (DataColumn dc in ds.Tables[0].Columns)
{
datagridView1.Columns.Add(dc.ColumnName, dc.ColumnName);
}
foreach (DataRow row in ds.Tables[0].Rows)
{
datagridView1.Rows.Add(row.ItemArray);
}
...
On this solution I have to wait until the ds.Tables[0].Rows
finishes, and after that the datagridview display those rows.
I am asking for for a solution or suggestion where I can see live rows inserting on datagridview, similar with results on SQL Server after executing a query.
Upvotes: 0
Views: 1952
Reputation: 34
Or just use Databind?
private DataTable Dt = new DataTable();
dataGridView1.DataSource = Dt;
//do what ever
DataRow dataRow = Dt.NewRow();
//add data here to data row
Dt.Rows.Add(dataRow);
Though this wont fix you problem with your GUI locking, I suggest reading this.
Upvotes: 0
Reputation: 12993
The reason while the rows are not added immediately is the UI thread is busy executing the loop, it has no chance to repaint the UI while the loop has not finished.
Solutions:
Application.DoEvents()
"magic" call. <= There are a lot of people saying Application.DoEvents
are evil, I can get down votes for this.
Back in the early days of .NET I was really impressed by this magic call. This call pauses the on-going task (adding rows), and executes the pending UI stuffs like repainting the UI, processing mouse/keyboard events. So the UI can remain responsive, otherwise it will be frozen until the lengthy task has finished.
So the code looks like this - Of course, calling it once for each row would be a performance disaster as explained in the comments.
foreach (DataRow row in ds.Tables[0].Rows)
{
datagridView1.Rows.Add(row.ItemArray);
Application.DoEvents();
}
BeginInvoke
, which accepts a delegate.The difference between the BeginInvoke
and directly executing the loop on the UI thread is BeginInvoke
is asynchronous. Here is an article explaining BeginInvoke
. (WOW, I did not expect it has been available since .NET 2.0, a time like a century ago).
Here is an example of adding rows to DataGridView using BeginInvoke.
Upvotes: 2