Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

c# - How to suspend a DataGridView while updating its columns

How can I suspend a .NET DataGridView from displaying anything while I update its Columns?

Here's my current code. It works ok, but it is very slow on the foreach loop; you can see the horiz scroll bar grow slowly as each column is added. I'm building the UI columns myself as I do not want to use dataGridView1.AutoGenerateColumns for various reasons.

// Disconnect and reset DataGridView
dataGridView1.DataSource = null;
dataGridView1.SuspendLayout();
dataGridView1.Columns.Clear();

// Get data from SQL
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("select * from employeehist", conn);
adapter.Fill(dt);

// Build DataGridView columns
foreach (DataColumn c in dt.Columns)
{
    DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
    col.SortMode = DataGridViewColumnSortMode.NotSortable;
    col.DataPropertyName = c.ColumnName;
    col.HeaderText = c.Caption;
    dataGridView1.Columns.Add(col);
}

// Reconnect DataGridView
dataGridView1.DataSource = dt;
dataGridView1.ResumeLayout(true);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use VirtualMode with DataGridView in order to very efficiently update the grid. See this article: http://msdn.microsoft.com/en-us/library/ms171622.aspx

From what I remember, it seems to update the entire collection before updating anything on the UI, as opposed to adding to the UI for each new row added/etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...