DataGridView行的背景颜色没有变化
我想根据加载时的特定条件更改DGV行的背景颜色,即使在Windows窗体中也是如此。 但我看不到任何DGV行的颜色变化。 谁能告诉我怎样才能解决这个问题?
private void frmSecondaryPumps_Load(object sender, EventArgs e) { try { DataTable dt = DeviceData.BindData("SECONDARY_PUMPS".ToUpper()); dataGridView1.DataSource = dt; foreach (DataGridViewRow row in dataGridView1.Rows) { foreach (DataGridViewColumn column in dataGridView1.Columns) { if (row.Cells[column.Name] != null) { if (row.Cells[column.Name].Value.ToString() == "ON") row.DefaultCellStyle.BackColor = System.Drawing.Color.Green; if (row.Cells[column.Name].Value.ToString() == "OFF") row.DefaultCellStyle.BackColor = System.Drawing.Color.Red; } } } dataGridView1.Refresh(); } catch (Exception err) { MessageBox.Show(err.Message); } }
我认为最好的地方是在DataGridView
的CellFormatting
事件中设置BackColor,这些就是这些行。
private void grid1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { DataGridViewRow row = grid1.Rows[e.RowIndex];// get you required index // check the cell value under your specific column and then you can toggle your colors row.DefaultCellStyle.BackColor = Color.Green; }
使用cellformatting
, databindingcomplete
或甚至paint
事件的问题之一是它们被多次触发。 从我收集的内容来看, datagridview
控件存在一个问题,即在显示表单之后,您无法更改任何单元格的颜色。 因此,在调用Shown()
之前运行的方法或触发的事件不会改变颜色。 作为问题解决方案的事件通常有效,但由于它们被多次调用,可能不是最有效的答案。
可能最简单的解决方案是将代码填入/填充表单的Shown()
方法中的网格而不是构造函数。 下面是msdn论坛中一篇post的链接,该post向我提供了解决方案,它被标记为关于页面下方3/4的答案。
MSDN论坛发布了解决方案
King_Rob是正确的。 我有同样的问题所以我将发布我的实施,因为这里的其他建议远非最佳。
添加事件处理程序(在设计器或构造函数中):
this.Load += UserControl_Load; // or form or any control that is parent of the datagridview dataGridView1.VisibleChanged += DataGridView1_VisibleChanged;
在load事件中,hander方法添加一个标志
private bool _firstLoaded; private void UserControl_Load(object sender, EventArgs e) { _firstLoaded = true; }
最后在可见事件处理程序方法中:
private void DataGridView1_VisibleChanged(object sender, EventArgs e) { if (_firstLoaded && dataGridView1.Visible) { _firstLoaded = false; // your code } }
对不起,迟到的答案,但我现在只是面对完全相同的问题。
对于在构造函数中无法正常工作的东西,我有一些通用的解决方案 – 使用计时器
将它设置为短时间,如100毫秒。 然后在构造函数中你将拥有
timer1.Enabled=true
并在timer_Tick事件中:
timer1.Enabled=false and all the code that doesn't work in constructor goes here...
它每次都对我有用。
这段代码快速,简单,不占用内存!
例如,在CellEndEdit事件中使用此代码
`try{ //your code } catch(Exception){ //your exception } finally{ yourDataGridView.Visible = false; yourDataGridView.Visible = true; }
`