2010-11-01 45 views
9

我有一個DataGridView。我把它.DataSource道具是我自己的對象的的BindingList:一個BindingList<IChessItem>有條件的DataGridView格式化

我然後創建了一些列吧..

DataGridViewTextBoxColumn descColumn = new DataGridViewTextBoxColumn(); 
    descColumn.DataPropertyName = "Description"; 
    descColumn.HeaderText = "Description"; 
    descColumn.Width = 300; 

    DataGridViewTextBoxColumn gameIDColumn = new DataGridViewTextBoxColumn(); 
    gameIDColumn.DataPropertyName = "GameID"; 
    gameIDColumn.HeaderText = "Game ID"; 
    gameIDColumn.Width = 60; 

    dataGrid.Columns.Add(descColumn); 
    dataGrid.Columns.Add(gameIDColumn); 

我的問題是..我要的顏色中的一列GREEN基於我的BindingList的另一個字段中的數據)。我怎樣才能做到這一點?

我真的沒有顯示這個領域,我只是想讓其中的數據採取行動..

在我的情況

,IChessItem的領域之一顯示記錄是否是新的,我想要爲datagridview中的其他字段着色以反映這一點。

回答

21

您可以使用DataGridView的'CellFormatting'事件。 DataGridViewCellFormattingEventArgs包含當前單元格的行和列在綁定時的索引。我希望我的代碼示例有一定道理給你:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    // Compare the column to the column you want to format 
    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "ColumnName") 
    { 
     //get the IChessitem you are currently binding, using the index of the current row to access the datasource 
     IChessItem item = sourceList[e.RowIndex]; 
     //check the condition 
     if (item == condition) 
     { 
      e.CellStyle.BackColor = Color.Green; 
     } 
    } 
} 
+0

有趣。這看起來像應該工作,不幸的是,當它到達這裏時,this.dataGridView1.Columns [e.ColumnIndex] .Name將返回「」。它看起來像*應該*工作。 – KevinDeus 2010-11-02 06:02:33

+0

okok ..我通過使用.DataPropertyName(因爲這是在我的代碼中設置的),並指向它返回到datagrid項目(因爲我的sourcelist已被擦除此點..)IChessItem item = ((BindingList )this.dgvAvailableMoves.DataSource)[e.RowIndex]; – KevinDeus 2010-11-02 06:14:09

+2

更強大的方法是直接比較列而不是檢查列名,即'if(dataGridView.Columns [e.ColumnIndex] == dataGridViewColumnXXX)...' – 2013-10-31 23:10:55

0

您可以使用填充任何循環或數據源在您的DataGridView數據。然後對於DataGridView1.Rows中的每個DataGridViewRow ----

Chk的ref值ypu想要chk然後設置DataGridviewCell [index] .style.backColor屬性。

+5

請不要這樣去格式化單元格 - 如果您有10000行x 20列,則將檢查200000個單元格。另一方面,如果您將使用CellFormatting事件,則您只對可見單元格進行格式設置(它的速度更快)。 – zeroDivisible 2012-03-13 11:25:11