' System.Windows.Forms.DataGridViewRow'不包含' BackColor'的定义

时间:2014-06-22 02:04:51

标签: c# winforms datagridview

我试图使用此代码更改Background中某行的DataGridView

DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[RowNumber].Clone();
row.Cells[1].Value = "Hey World";
row.BackColor = System.Drawing.Color.Gray;

但在第三行是这个错误:

  

'System.Windows.Forms.DataGridViewRow'不包含'BackColor'的定义,并且没有扩展方法'BackColor'接受类型'System.Windows.Forms.DataGridViewRow'的第一个参数可以找到(你错过了吗?) using指令或程序集引用?)

1 个答案:

答案 0 :(得分:2)

您收到该错误是因为DataGridViewRow没有此类属性。

您可以通过修改BackColor来更改单行的DefaultCellStyle

dataGridView1.Rows[2].DefaultCellStyle.BackColor = Color.Gray;

您还可以将DataGridView订阅到CellFormatting事件并在其中放置一些逻辑以确定哪些行需要具有不同的背景颜色:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.RowIndex % 2 == 0)
        e.CellStyle.BackColor = Color.Gray;
}

上面的代码会将每隔一行的背景颜色更改为灰色。

(这只是一个人为的例子,因为如果你真的想要交替的行颜色,你就要改变AlternatingRowsDefaultCellStyle属性。)

相关问题