【问题标题】:How to get DataGridViewRow from CellFormatting event?如何从 CellFormatting 事件中获取 DataGridViewRow?
【发布时间】:2009-10-15 12:58:30
【问题描述】:

我有一个 DataGridView 并处理事件 CellFormatting。它有一个参数叫做:

DataGridViewCellFormattingEventArgs e

e.RowIndex 在里面。

当我这样做时:

DataGridView.Rows[e.RowIndex] 

我从集合中得到了正确的行。

但是,当我单击列的标题以按默认列和用户 DataGridView.Rows[e.RowIndex] 以外的其他列对其进行排序时,我得到了不正确的行。

这是因为 Rows 集合不反映 DataGridView 中行的顺序。

那么如何从DataGridView中的RowIndex获取属性DataGridViewRow呢?

【问题讨论】:

    标签: c# .net winforms datagridview


    【解决方案1】:

    如果我的理解是正确的,您希望根据数据源中的索引而不是显示索引对某些行执行格式化。在这种情况下,您可以使用 DataGridViewRow 的 DataBoundItem 属性。考虑到你的数据源是一个数据表,这个项目将是一个 DataGridViewRow,它有一个名为 Row 的属性,你可以在原始数据源中找到它的索引。看下面的例子:

    DataTable t = new DataTable(); //your datasource
    int theIndexIWant = 3;
    
    private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {               
        DataRowView row = dataGridView1.Rows[e.RowIndex].DataBoundItem as DataRowView;      
    
        if (row != null && t.Rows.IndexOf(row.Row) == theIndexIWant)
        {
            e.CellStyle.BackColor = Color.Red;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 2010-12-22
      • 2019-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多