2017-07-25 112 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 –

相关问题