简体   繁体   English

如何检查DataGridView中的单元格是否存在?

[英]How to check if a cell in DataGridView exist?

I have a static method that check the sum of an given column. 我有一个静态方法来检查给定列的总和。 I am using it on event RowsAdded but I got the following error: 我在事件“行RowsAdded上使用它,但出现以下错误:

System.NullReferenceException was unhandled
Message=Object reference not set to an instance of an object.

Here is my code, please tell me where I am wrong 这是我的代码,请告诉我哪里错了

public static decimal datagSum(DataGridView dgv, string colName)
{
    int i = dgv.RowCount - 1, j = 0;
    decimal dgvSum = 0;
    decimal k = 0;
    while (j < i)
    {
        if (dgv.Rows[(i - 1)].Cells.Count > 3)
        {

            if (decimal.TryParse(dgv.Rows[(i - 1)].Cells[colName].Value.ToString(), out k))
            {
                dgvSum += k;
            }
            j++;

        }
    }
    return dgvSum;
}

Code Snippet 代码段

if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
   {
       if (String.IsNullOrEmpty(e.FormattedValue.ToString()))
       {
           dataGridView1.Rows[e.RowIndex].ErrorText =
               "Company Name must not be empty";
           e.Cancel = true;
       }
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM