2012-10-19 17 views
0

我想在DataGridView中格式化指定的行,但它不斷格式化我的DataGridView中的所有行。這是我在做什麼:DataGridView CellFormatting在指定的行和單元格

private void dgwParti_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
    { 
     foreach (DeParti tmp in bnsParti) 
     { 
      if (tmp.Arti.Type == ArtiType.Fast) 
      { 
       if (e.ColumnIndex == 0 || e.ColumnIndex == 3 || 
        e.ColumnIndex == 8 || e.ColumnIndex == 9) 
       { 
        e.Value = ""; 
       } 
      } 
     } 
    } 

使用這種類型的代碼,它不斷設置單元格的值「」,在所有的行,但我只想要那個值是「」,當ARTI類型是快速。有任何想法嗎。
在此先感謝。

+0

什麼是'bnsParti'? – Otiel

+0

@Otiel BindingSource – Brezhnews

回答

2

如果您必須格式化指定的行,您爲什麼要檢查列?

訪問DataBoundItem(與被格式化的行相關聯的對象)並根據您的邏輯修改Value。不要直接訪問綁定源。 你的代碼應該是

private void dgwParti_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    if ((Rows[e.RowIndex].DataBoundItem as DeParti).Arti.Type == ArtiType.Fast) 
    { 
     e.Value = ""; 
    } 
} 

這將「乾淨」的所有行中的細胞,你可以,如果你要設置的值僅適用於某些列增加一個檢查=「」,例如

private void dgwParti_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    if ((Rows[e.RowIndex].DataBoundItem as DeParti).Arti.Type == ArtiType.Fast 
     && e.ColumnIndex == 8) 
    { 
     e.Value = ""; 
    } 
} 
+1

也許首先檢查e.ColumnIndex屬性會快一點。 –

相關問題