问题描述
In the application I'm developing at the moment I'm using a datagridview to display data. To fill it, I've to press a button and a backgroundworker will start running, it will fill a datatable and when it's finished running it will use the datatable as the datasource for the datagrid. This works fine, the UI stays responsive et cetera.
But now I've implemented coloring to the rows, depending on their values (Im still playing around with it, so any suggestions are welcome):
这给我的问题。不是因为着色不起作用。但是因为它让hella慢。第一次运行正常,但是当我再次按下按钮时,它的速度很慢,而且datagrid正在闪烁。
我希望这个运行作为后处理,所以(或者更应该)在后台工作完成后运行。
但是当我从RunWorkerCompleted事件调用applycoloring时,它的速度很慢。我应该怎么做这样做?
private void ApplyColoring() { if (dataGridView1.DataSource != null) { foreach (DataGridViewRow dataGridRow in dataGridView1.Rows) { // hardmap a color to a column IDictionary<Int32, Color> colorDictionary = new Dictionary<Int32, Color>(); colorDictionary.Add( 7, Color.FromArgb(194, 235, 211)); colorDictionary.Add( 8, Color.Salmon); colorDictionary.Add( 9, Color.LightBlue); colorDictionary.Add(10, Color.LightYellow); colorDictionary.Add(11, Color.LightGreen); colorDictionary.Add(12, Color.LightCoral); colorDictionary.Add(13, Color.Blue); colorDictionary.Add(14, Color.Yellow); colorDictionary.Add(15, Color.Green); colorDictionary.Add(16, Color.White); foreach (DataGridViewRow gridRow in dataGridView1.Rows) { foreach (DataGridViewCell cell in gridRow.Cells) { if (colorDictionary.Keys.Contains(cell.ColumnIndex)) { // standard background cell.Style.BackColor = Color.FromArgb(194, 235, 211); } } } IList<String> checkedValues = new List<String>(); // first we loop through all the rows foreach (DataGridViewRow gridRow in dataGridView1.Rows) { IDictionary<String, Int32> checkedVal = new Dictionary<String, Int32>(); // then we loop through all the data columns int maxCol = dnsList.Count + 7; for (int columnLoop = 7; columnLoop < maxCol; columnLoop++) { string current = gridRow.Cells[columnLoop].Value.ToString(); for (int checkLoop = 7; checkLoop < maxCol; checkLoop++) { string check = gridRow.Cells[checkLoop].Value.ToString(); if (!current.Equals(check)) { if (checkedVal.Keys.Contains(current)) { gridRow.Cells[columnLoop].Style.BackColor = colorDictionary[checkedVal[current]]; } else { gridRow.Cells[columnLoop].Style.BackColor = colorDictionary[columnLoop]; checkedVal.Add(current, columnLoop); } } } } } } } }
推荐答案
- 尝试在循环之前调用SuspendLayout()并在循环后调用ResumeLayout()。大多数其他控件称为BeginUpdate()和EndUpdate()(Listviews,Combobox等)。
- 如果您处理大量
数据,则在DataGridView上使用VirtualMode。 / li>
- Try calling SuspendLayout() prior to the loop and ResumeLayout() after the loop. Most other controls call this BeginUpdate() and EndUpdate() (Listviews, Combobox's etc).
- Use VirtualMode on DataGridView if you're dealing with large amount ofdata.
这篇关于如何防止datagrid中的行在应用程序运行时闪烁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!