我有一个DataGridView,显示了一个DataTable的内容。
我想根据该行中一个单元格的值来设置行的背景颜色。
请注意,所涉及的单元格位于DataGridView中未显示的列中(Visible=False)。
我想根据该行中一个单元格的值来设置行的背景颜色。
请注意,所涉及的单元格位于DataGridView中未显示的列中(Visible=False)。
如前所述,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"; } } }注意:请勿删除HTML标签。
如果您处理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#,请告诉我。
祝您好运!
另一个选择是使用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;
}
}
// 选项二 -- 可以使用 ColumnIndex 而不是 ColumnName
private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView["ColumnName", e.RowIndex].Value).Condition == TargetValue)
{
e.CellStyle.BackColor = System.Drawing.Color.Gold;
}
}