2017-07-25 29 views
0

我想在DataGridView事件CellFormatting編寫代碼來觸發,如果在同一行的列(qtyscanqty)值是不同的,然後設置背景顏色比較黃的邏輯。但會發生運行時錯誤C# - 的DataGridView比較兩個單元格的值和設置風格

System.ArgumentOutOfRangeException:'索引超出範圍。必須是非負面的,並且小於收藏的大小。「

以下是我的示例代碼,任何人都可以幫助我,非常感謝。

private void dgProductList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    if (this.dgProductList.Columns[e.ColumnIndex].Name == "scanqty") 
    { 
     var sqty = String.IsNullOrEmpty(e.Value.ToString()) ? 0 : int.Parse(e.Value.ToString()); 
     var qty = int.Parse(dgProductList[e.RowIndex, 1].Value.ToString()); 

     if (sqty != qty) 
     { 
      e.CellStyle.BackColor = Color.Yellow; 
      e.CellStyle.ForeColor = Color.Red; 
     } 
     else 
     { 
      e.CellStyle.BackColor = Color.White; 
      e.CellStyle.ForeColor = Color.Black; 
     } 
    } 
} 

回答

1

當使用[ ]運營商在DataGridView語法訪問數據:

dgProductList[columnIndex, rowIndex] 

enter image description here 你正在做相反的方式。請改變這一行:

var qty = int.Parse(dgProductList[e.RowIndex, 1].Value.ToString()); 

這樣:

var qty = int.Parse(dgProductList[1, e.RowIndex].Value.ToString()); 

另一種可能使用的列名qty

var qty = int.Parse(dgProductList["qty", e.RowIndex].Value.ToString()); 
+0

哇,粗心的錯誤,謝謝。 –

+0

沒問題。在StackOverflow上表達謝意的最佳方式是將答案標記爲已接受。如果你不知道如何去做,這裏是[解釋它的帖子](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。祝你有個美好的一天 –

1

考慮這樣的事情,因爲性能原因:

private void dgProductList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    if (e.ColumnIndex == COL_INDEX_OF_SCANQTY_COLUMN) 
    { 
     var sqty = (DATATYPE_OF_SCANQTY)e.Value; 
     var qty = (DATATYPE_OF_QTY)dgProductList[1, e.RowIndex].Value; 

     if (sqty != qty) 
     { 
      e.CellStyle.BackColor = Color.Yellow; 
      e.CellStyle.ForeColor = Color.Red; 
     } 
     else 
     { 
      e.CellStyle.BackColor = Color.White; 
      e.CellStyle.ForeColor = Color.Black; 
     } 
    } 
} 

你不需要從字符串返回到int等。你也很高興硬編碼的QTY總是列1,但你查找scanqty列的名稱,並將其與字符串進行比較,以檢查它是否是在scanqty列 - 你不如硬代碼,也

如果你不知道該值的數據類型,在調試器暫停,看一看..

+0

明白了。謝謝。 –

1

至於其他的答案可能是正確的,我認爲這裏真正的問題是e.RowIndexe.ColumnIndex可以是-1(例如爲標題行)。因此,您必須先檢查這些指數是否爲>= 0,並忽略帶有-1的那些指數。

private void dgProductList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    if (e.ColumnIndex >= 0 && this.dgProductList.Columns[e.ColumnIndex].Name == "scanqty") 
    { 
     // ... 
    } 
} 
+0

我誤解了第一個數據行索引是0,第一列索引是0 –

相關問題