【问题标题】:C# - Datagridview compare two cells value and set styleC# - Datagridview 比较两个单元格的值并设置样式
【发布时间】:2017-07-25 16:54:15
【问题描述】:

我正在尝试在DataGridView 事件CellFormatting 中编写代码以触发比较同一行中的列(qtyscanqty)值是否不同的逻辑,然后将背景颜色设置为黄色。但是出现运行时错误

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;
        }
    }
}

【问题讨论】:

    标签: c# .net winforms datagridview


    【解决方案1】:

    当使用[ ] 运算符访问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());
    

    【讨论】:

    • 没问题。在 StackOverflow 上表示感谢的最佳方式是将答案标记为已接受。如果你不知道怎么做,这里是a post that explains it。祝你有美好的一天
    【解决方案2】:

    出于性能原因考虑这样的事情:

    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;
            }
        }
    }
    

    您不需要从 string 往返返回 int 等。此外,您很乐意硬编码 QTY 始终是第 1 列,但您查找 scanqty 的列名称并将其与 string 进行比较以检查如果是 scanqty 列 - 你也可以硬编码

    如果您不知道值的数据类型,请在调试器中暂停并查看..

    【讨论】:

    • 知道了。谢谢。
    【解决方案3】:

    由于其他答案可能是正确的,我认为这里的真正问题是 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
    猜你喜欢
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多