c# - 条件 DataGridView 格式化

标签 c# winforms datagridview

我有一个 DataGridView。我将其 .DataSource Prop 设置为我自己的对象的 BindingList:BindingList<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);

我的问题是.. 我想根据 BindingList 的另一个字段中的数据将其中一列着色为绿色。我该怎么做?

我真的不需要显示这个字段,我只想对其中的数据采取行动..

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

最佳答案

您可以使用 DataGridView 的“CellFormatting”事件。 DataGridViewCellFormattingEventArgs 包含绑定(bind)当前单元格的行和列的索引。我希望我的代码示例对您有所帮助:

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;
        }
    }
}

关于c# - 条件 DataGridView 格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4067068/

相关文章:

c# - 尝试使用 Entity Framework 核心执行更新存储过程时出错

c# - 在单独的线程上创建 WebBrowser 控件

c# - WinForms:在多行文本框中自动完成

c# - DataGridView 性能与 BindingList 数据源相结合

c# - 如何从代码隐藏加密在 web.config 中编写的连接字符串?

c# - 结构值列表和数组与变量

C# 带参数的存储过程

c# - 按下按钮即可播放声音

c# - 如何确定用户单击了 DataGridView 而不是 Cell

c# - 如何在 c# 中使用行索引和列索引从 datagridview 获取单元格值?