2011-10-06 100 views
0

我有一個數據網格視圖,想知道是否可以只突出顯示包含特定列值的特定行。DataGridView中的不同顏色的線(DGV)

所以我想所有的行默認爲黑色的白色文本,除了任何具有指定列的行等於FUJI/UNIVERSAL。對於這一行,我希望它是帶有黑色文字的黃色。

所以我的問題是......這是可能的嗎?如果是這樣,怎麼樣?

回答

2

最好的地方就是DataGridView的RowPrePaint事件。

這裏是你如何實現這一目標。

void dataGridView1_RowPrePaint(object sender, 
     DataGridViewRowPrePaintEventArgs e) 
{ 
    if (dataGridView1.Rows[e.RowIndex].Cells[0].Value == "YourConditionalValue") 
    { 
     dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow; 
    } 
} 
+0

最簡單和最短的代碼。謝謝! – theNoobGuy

1

處理DataGridView控件的OnPaint事件。

解析所有行,並在具有您要查找的信息的行上設置顏色。

一些示例代碼:

int specificColumnIndex = 5; 
const string FUJIUNIV = "FUJI/UNIVERSAL"; 
const Color cFUJIBACK = Color.Yellow; 
const Color cFUJITEXT = Color.Black; 

public Form1() { 
    InitializeComponent(); 
    dataGridView1.Paint += new PaintEventHandler(DataGridView_Paint); 
} 

private void DataGridView_Paint(object sender, PaintEventArgs e) { 
    foreach (DataGridViewRow row in dataGridView1.Rows) { 
    if (row.Cells[specificColumnIndex].Value.ToString() == FUJIUNIV) { 
     foreach (DataGridViewCell cell in row.Cells) { 
     cell.Style.BackColor = cFUJIBACK; 
     cell.Style.ForeColor = cFUJITEXT; 
     cell.Style.SelectionBackColor = Color.Gold; 
     } 
    } 
    } 
} 

}

1

例如通過處理OnCellFormatting事件。

下面是我的一箇舊的WinForms愛好項目中的一段代碼,它完全是這樣。它也再次教給我評論的重要性(我現在還沒有機會記住它)。

我確信你可以適應你的目的。

private void sheetCalendar_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
    { 
     if (CurrentRota == null) 
     { 
      return; 
     } 
     /* A word of explanation is needed. We retrieve the DataGridView from sender 
     * and we access the cell in question directly. 
     * MSDN advices against it - 
     * "to avoid performance penalties When handling this event, 
     * access the cell through the parameters of the event handler 
     * rather than accessing the cell directly." 
     * 
     * The problem is that we don't want to set the same colour to the same cell 
     * over and over again. 
     * And e.CellStyle always "forgets" what colour the call had had! */ 
     var dgrid = sender as DataGridView; 
     var _col = e.ColumnIndex; 
     var _row = e.RowIndex; 
     var _highlight = (((Rota) sheetCalendar.Rows[e.RowIndex].DataBoundItem).Monday == 
          CurrentRota.Monday); 
     var color = _highlight ? 
            Settings.Default.DGRIDCalendar_CurrentlyEditedBackColor : 
                           SystemColors.Window; 
     if (dgrid[_col, _row].Style.BackColor != color) 
      dgrid[_col, _row].Style.BackColor = color; 

    }