下面是一个根据DataGridView列的值,改变行的颜色的例子。
实现这个并不困难,属性不会总是在我们想象的那个地方。这个属性隐藏在行的DefaultCellStyle 属性中。
代码
foreach (DataGridViewRow row in mydataGridView.Rows)
{
string RowType = row.Cells[0].Value.ToString();
if (RowType == "Type A")
{
row.DefaultCellStyle.BackColor = Color.Red;
row.DefaultCellStyle.ForeColor = Color.White;
{
string RowType = row.Cells[0].Value.ToString();
if (RowType == "Type A")
{
row.DefaultCellStyle.BackColor = Color.Red;
row.DefaultCellStyle.ForeColor = Color.White;
}
else if (RowType == "Type B")
{
row.DefaultCellStyle.BackColor = Color.Yellow;
row.DefaultCellStyle.ForeColor = Color.Black;
}
}
添加上面这段代码到UpdateDataGridViewRowColors() 方法中,你的DataGridView绑定或者从新绑定数据的时候调用它。