[英]C# - Datagridview compare two cells value and set style
我正在嘗試在DataGridView
事件CellFormatting
編寫代碼以觸發邏輯,該邏輯將比較同一行中的列( qty
和scanqty
)值是否不同,然后將背景色設置為Yellow。 但是發生運行時錯誤
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;
}
}
}
當使用[ ]
運算符訪問DataGridView
的數據時,語法為:
dgProductList[columnIndex, rowIndex]
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());
考慮到性能,請考慮這樣的事情:
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列-您也可能會進行硬編碼
如果您不知道值的數據類型,請在調試器中將其暫停並查看。
由於其他答案可能是正確的,我認為這里的真正問題是e.RowIndex
和e.ColumnIndex
可以為-1(例如對於標題行)。 因此,您必須首先檢查這些索引是否>= 0
並忽略那些具有-1的索引。
private void dgProductList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex >= 0 && this.dgProductList.Columns[e.ColumnIndex].Name == "scanqty")
{
// ...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.