简体   繁体   中英

After adding a new row in datagridview, display it immediately

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.

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:

  1. The old 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(); 
}
  1. Use 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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM