Sta*_*ust 15 .net c# datagridview winforms
我想根据加载时的特定条件更改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);
}
}
Run Code Online (Sandbox Code Playgroud)
V4V*_*tta 14
我认为最好的地方是设置背景色中CellFormatting的情况下DataGridView,一些在这些线路上.
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;
}
Run Code Online (Sandbox Code Playgroud)
小智 12
一个使用任一的问题cellformatting,databindingcomplete甚至paint事件是,他们被解雇多次.从我收集的内容来看,datagridview控件存在一个问题,即在表单显示之后,您无法更改任何单元格的颜色.因此,运行的方法或之前触发的事件Shown()将不会更改颜色.作为问题解决方案的事件通常有效,但由于它们被多次调用,可能不是最有效的答案.
可能最简单的解决方案是将代码填入/填充Shown()表单方法中的网格而不是构造函数.下面是msdn论坛中一篇帖子的链接,该帖子向我提供了解决方案,它被标记为关于页面下方3/4的答案.
King_Rob 是正确的。我有同样的问题,所以我只会发布我的实现,因为这里的其他建议远非最佳。
添加事件处理程序(在设计器或构造器中):
this.Load += UserControl_Load; // or form or any control that is parent of the datagridview
dataGridView1.VisibleChanged += DataGridView1_VisibleChanged;
Run Code Online (Sandbox Code Playgroud)
在加载事件处理程序方法中添加一个标志
private bool _firstLoaded;
private void UserControl_Load(object sender, EventArgs e)
{
_firstLoaded = true;
}
Run Code Online (Sandbox Code Playgroud)
最后在可见事件处理程序方法中:
private void DataGridView1_VisibleChanged(object sender, EventArgs e)
{
if (_firstLoaded && dataGridView1.Visible)
{
_firstLoaded = false;
// your code
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33443 次 |
| 最近记录: |