& # 39; System.Windows.Forms.DataGridViewRow& # 39;不包含'B

本文关键字:包含 Windows System Forms DataGridViewRow | 更新日期: 2023-09-27 18:09:37

我试图用这个代码改变DataGridView中一行的Background

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指令或程序集引用?)

& # 39; System.Windows.Forms.DataGridViewRow& # 39;不包含'B

你得到这个错误,因为DataGridViewRow没有这样的属性。

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

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属性)