条件DataGridView格式

Kev*_*eus 13 c# datagridview winforms

我有一个DataGridView.我将其.DataSource prop设置为我自己对象的BindingList:aBindingList<IChessItem>

然后我为它创建了一些列..

    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);
Run Code Online (Sandbox Code Playgroud)

我的问题是..我想根据我BindingList的另一个字段中的数据为其中一列GREEN着色.我怎样才能做到这一点?

我真的不必显示这个字段,我只想对其中的数据进行操作..

在我的例子中,IChessItem的一个字段显示记录是否是新的,我想为datagridview中的其他字段着色以反映这一点.

Edw*_*ing 26

您可以使用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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 一种更健壮的方法是直接与列进行比较而不是检查列名,即`if(dataGridView.Columns [e.ColumnIndex] == dataGridViewColumnXXX)...` (2认同)