簡體   English   中英

如何更改數據網格的特定行的顏色

[英]How can i change the color of particular row of a datagrid

我將數據表綁定到datagrid我只想根據datatable行上的值更改特定行datagrid的顏色。 我需要c#/ .net代碼

網格視圖具有一種控制樣式的屬性層次結構。 這里有一個很好的概述:

http://msdn.microsoft.com/en-us/library/1yef90x0.aspx

但最簡單的說,您可以為未選擇的行設置DataGridViewRow.DefaultCellStyle.SelectionBackColor屬性,為所選行設置DataGridViewRow.DefaultCellStyle.BackColor屬性。

就像是:

this.dataGridView1.Rows[RowIndex].DefaultCellStyle.BackColor = Color.Yellow;

或者,如果你想通過鼠標移動事件

private void DataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
dataGridView1[e.ColumnIndex, e.RowIndex].Style.SelectionBackColor = Color.Red;
}

private void DataGridView_CellLeave1(object sender, DataGridViewCellEventArgs e)
{
dataGridView1[e.ColumnIndex, e.RowIndex].Style.SelectionBackColor = Color.Blue;
}

此外, 根據列值更改單個DataGridView行顏色可能會有所幫助。

如果要根據行的內容而不是選擇狀態更改所選行的外觀,我就是這樣做的:

   private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (RowShouldBeRed(e))
        {
            e.CellStyle.BackColor = Color.LightPink;
            e.CellStyle.SelectionBackColor = Color.Red;
        }
        else
        {
            e.CellStyle.BackColor = DataGridView1.DefaultCellStyle.BackColor;
            e.CellStyle.SelectionBackColor = DataGridView1.DefaultCellStyle.SelectionBackColor;
        }
    }

在此示例中,RowShouldBeRed函數是用於確定如何為行着色的邏輯的存根。

//對於特定的細胞

dataGridView1.Rows[RowIndex].Cells[ColumnIndex].Style.BackColor = Color.Red;

//對於特定的行

dataGridView1.Rows[RowIndex].DefaultCellStyle.BackColor = Color.Black;

//對於特定列

dataGridView1.Columns[ColumnIndex].DefaultCellStyle.BackColor =Color.Yellow;

暫無
暫無

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

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