简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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