簡體   English   中英

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

[英]'System.Windows.Forms.DataGridViewRow' does not contain a definition for 'BackColor'

我試圖用此代碼更改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指令或裝配參考?)

您收到該錯誤,因為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屬性。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM