如何从CellFormatting事件获取DataGridViewRow? [英] How to get DataGridViewRow from CellFormatting event?

查看:48
本文介绍了如何从CellFormatting事件获取DataGridViewRow?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a DataGridView and handle event CellFormatting. It has a parameter called:

DataGridViewCellFormattingEventArgs e

使用

其中的e.RowIndex.

e.RowIndex in it.

当我这样做时:

DataGridView.Rows[e.RowIndex] 

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

I get proper row from collection.

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

But when I click at a header of a column to sort it by other column than default one and user DataGridView.Rows[e.RowIndex] I get unproper row.

这是因为行"集合不能反映DataGridView中行的顺序.

It is because Rows collection do not reflect order of rows in DataGridView.

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

So how to get propert DataGridViewRow from RowIndex in DataGridView?

推荐答案

如果我的理解是正确的,则希望基于数据源中某些行的索引而不是基于显示索引来对某些行进行格式化.在这种情况下,可以使用DataGridViewRow的DataBoundItem属性.考虑到您的数据源是一个数据表,此项目将是一个DataGridViewRow,它具有一个名为Row的属性,您可以在其原始数据源中找到索引.参见下面的示例:

If my understanding is correct, you want to perform formatting for certain rows based on their index in the datasource, not based on the display index. In this case, you can use the DataBoundItem property of the DataGridViewRow. Considering that your datasource is a datatable, this item will be a DataGridViewRow, which has a property called Row, for which you can find the index in your original datasource. See below an example:

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

这篇关于如何从CellFormatting事件获取DataGridViewRow?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆