C# 如何使用不同的颜色初始化datagrid中的某些行?
我想根据特定条件以红色初始化我的DataGridView的一些行。问题是,我一直在玩,但当显示DataGridView时,我无法让它工作。我尝试在MainForm的构造函数中执行此操作,但一点运气都没有C# 如何使用不同的颜色初始化datagrid中的某些行?,c#,winforms,c#-4.0,C#,Winforms,C# 4.0,我想根据特定条件以红色初始化我的DataGridView的一些行。问题是,我一直在玩,但当显示DataGridView时,我无法让它工作。我尝试在MainForm的构造函数中执行此操作,但一点运气都没有 private void UpdateSoldOutProducts () { for (int i = 0; i < productsTable.Rows.Count; i++) if ((int)productsTable.Rows [i
private void UpdateSoldOutProducts ()
{
for (int i = 0; i < productsTable.Rows.Count; i++)
if ((int)productsTable.Rows [i] ["Quantity"] == 0)
dataGridViewProducts.Rows [i].DefaultCellStyle.BackColor = Color.Red;
}
private void UpdateSoldOutProducts()
{
for(int i=0;i
此方法是在主窗体的构造函数中调用的。尝试RowPostPaint事件,它适用于我:
private void dataGridViewProducts_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
if ((int)dataGridViewProducts.Rows[e.RowIndex].Cells["Quantity"].Value == 0)
dataGridViewProducts.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
}
可以使用自定义绘制绘制DataGridView行和单元格。就这样结束了 和 另一个期望是
绘制事件
private void dataGridViewProducts_Paint(object sender, PaintEventArgs e)
{
foreach (DataGridViewRow row in dataGridViewProducts.Rows)
{
int value = Convert.ToInt32(row.Cells["Quantity"].Value);
if (value == 0)
row.DefaultCellStyle.BackColor = Color.Red;
}
}
可以使用DataGridViewRowPostPaintEventArgs或DataGridViewRowPrePaintEventArgs根据条件设置行或单元格样式
您可以单独处理此事件,也可以与RowPrePaint
事件一起处理,以自定义控件中行的外观。您可以自己绘制整个行,或绘制行的特定部分,并使用DataGridViewRowPostPaintEventArgs
类的以下方法绘制其他部分:
- 牵引焦点
- 油漆槽
- 油漆槽背景
- 画室内容
- 油漆工
在MSDN链接上检查此示例,并尝试编写其中一个事件的代码。。在这里,您将使用DataGridViewRowPostPaintEventArgs获取当前行索引
编辑:
将代码放在窗体加载事件或数据绑定完成事件上。希望这能解决您的问题。我们尝试将我的代码放在Form\u Load方法中,但什么也没发生。我将尝试绘画或预绘画活动。我不明白的是DataGridView的绘制或预绘制事件将使用DefaultCellStyle.BackColor绘制单元格的颜色。那么,如果我改变属性BackColor的值,为什么我必须自己处理绘制事件?兄弟,你是否尝试过RowPostPaint,因为它工作得非常好?我的朋友,但我会尝试。我没有试过。谢谢你所有的帮助:)嗨,阿门,我继续处理了推迟事件。它就像一个符咒!而且,这样做更好,我不必每次更新datagrid中的某些内容时都遍历整个表。再次感谢。
int value = Convert.ToInt32(dataGridViewProducts.Rows[e.RowIndex].Cells["Quantity"].Value);
if (value == 0)
dataGridViewProducts.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;