How to get DataGridViewRow from CellFormatting event?

不问归期 提交于 2021-02-08 10:41:29

问题


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

DataGridViewCellFormattingEventArgs e

With

e.RowIndex in it.

When i do:

DataGridView.Rows[e.RowIndex] 

I get proper row from collection.

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.

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

So how to get propert DataGridViewRow from RowIndex in DataGridView?


回答1:


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


来源:https://stackoverflow.com/questions/1572213/how-to-get-datagridviewrow-from-cellformatting-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!