如何根据单元格的值更改DataGridView中行的背景颜色?
问题描述:
我有一个DataGridView显示一个DataTable的内容。如何根据单元格的值更改DataGridView中行的背景颜色?
我想根据此行中单元格的值设置行的背景颜色。
请注意有问题的单元格在DataGridView(Visible = False)中未显示的列中。
答
如果处理RowDataBound事件,则可以检查数据的值并修改单元格的属性或在该事件处理程序中应用不同的样式。
protected void Page_Load(object sender, EventArgs e)
{
GridView g1 = new GridView();
g1.RowDataBound += new GridViewRowEventHandler(g1_RowDataBound);
}
void g1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Check the Value
if(e.Row.Cells[1].Text = someValue)
{
e.Row.Cells[1].CssClass = "colorCellRed";
}
}
}
这应该会给你你想要的。让我知道如果你需要它在VB而不是C#。
祝你好运!如已经提到的,RowDataBound;
答
RowDataBound,你也可以检查你的数据对象的值,以及文本中网格本身:
void gridView_DataBound(object sender, GridViewEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { var myObject = (myObject)e.DataItem; if (myObject.IsOverdue()) { e.Row.CssClass = "overdue"; } } }
答
另一种选择是使用CellFormatting事件。 第一个选项显示访问绑定的数据项,并且如果您没有为有问题的数据设置列,这会很有用。如果列中有可见或不可见,则第二个选项有效。
private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (((MyDataObject)dataGridView.Rows[e.RowIndex].DataBoundItem).Condition == Value)
{
e.CellStyle.BackColor = System.Drawing.Color.Gold;
}
}
//办法二 - 可以用它代替的ColumnName
ColumnIndexprivate void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView["ColumnName", e.RowIndex].Value).Condition == TargetValue)
{
e.CellStyle.BackColor = System.Drawing.Color.Gold;
}
}