如何从CellFormatting事件中获取DataGridViewRow?
问题描述:
我有一个DataGridView和句柄事件CellFormatting。它有一个叫做参数:如何从CellFormatting事件中获取DataGridViewRow?
DataGridViewCellFormattingEventArgs e
随着
e.RowIndex在里面。
当我这样做:
DataGridView.Rows[e.RowIndex]
我从收集正确的行。
但是,当我点击一列的标题来排序它比其他列而不是默认的一个和用户DataGridView.Rows [e.RowIndex]我得到不正确的行。
这是因为行集合不反映DataGridView中行的顺序。
那么如何从DataGridView的RowIndex中获取属性DataGridViewRow?
答
如果我的理解是正确的,您希望根据数据源中的索引对某些行执行格式设置,而不是基于显示索引。在这种情况下,您可以使用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;
}
}