【问题标题】:Conditional DataGridView Formatting条件 DataGridView 格式
【发布时间】:2011-05-03 07:07:35
【问题描述】:

我有一个 DataGridView。我将其 .DataSource 属性设置为我自己的对象的 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 中的其他字段着色以反映这一点。

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    您可以使用 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;
            }
        }
    }
    

    【讨论】:

    • 有趣。不幸的是,这看起来应该可以工作, this.dataGridView1.Columns[e.ColumnIndex].Name 每当它到达这里时都会返回“”。看起来它应该工作。
    • okok.. 我通过使用 .DataPropertyName (因为这是在我上面的代码中设置的)让它工作,并将它指向 datagrid 项(因为我的源列表已被此删除点..) IChessItem item = ((BindingList) this.dgvAvailableMoves.DataSource)[e.RowIndex];
    • 一种更健壮的方法是直接比较列而不是检查列名,即if (dataGridView.Columns[e.ColumnIndex] == dataGridViewColumnXXX) ...
    【解决方案2】:

    您可以使用任何循环或数据源在 DataGridView 中填充数据。然后对于DataGridView1.Rows中的每个DataGridViewRow----

    检查你想要检查的 ref 值,然后设置 DataGridviewCell[index].style.backColor 属性。

    【讨论】:

    • 请不要这样格式化单元格 - 如果您有 10000 行 x 20 列,您将检查 200000 个单元格。另一方面,如果您将使用 CellFormatting 事件,则仅对可见单元格进行格式化(这要快得多)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 2018-02-17
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多