如何从CellFormatting事件中获取DataGridViewRow?

时间:2009-10-15 12:58:30

标签: c# .net winforms datagridview

我有一个DataGridView并处理事件CellFormatting。它有一个名为:

的参数
DataGridViewCellFormattingEventArgs e

e.RowIndex in。

当我这样做时:

DataGridView.Rows[e.RowIndex] 

我从收集中获得了正确的行。

但是当我点击一个列的标题以按照默认值和用户DataGridView.Rows [e.RowIndex]之外的其他列对其进行排序时,我得到了不合适的行。

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

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

1 个答案:

答案 0 :(得分:2)

如果我的理解是正确的,您希望根据数据源中的索引执行某些行的格式化,而不是基于显示索引。在这种情况下,您可以使用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;
    }
}