2009-10-15 90 views
0

我有一個DataGridView和句柄事件CellFormatting。它有一個叫做參數:如何從CellFormatting事件中獲取DataGridViewRow?

DataGridViewCellFormattingEventArgs e 

隨着

e.RowIndex在裏面。

當我這樣做:

DataGridView.Rows[e.RowIndex] 

我從收集正確的行。

但是,當我點擊一列的標題來排序它比其他列而不是默認的一個和用戶DataGridView.Rows [e.RowIndex]我得到不正確的行。

這是因爲行集合不反映DataGridView中行的順序。

那麼如何從DataGridView的RowIndex中獲取屬性DataGridViewRow?

回答

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; 
    } 
} 
相關問題