Hunar
Hunar

Reputation: 399

check numeric value of a datagrdiview cell value?

In my project, I have a datagridview with some columns, one of the columns have a numeric value. I want to perform a check for this cell value but it gives me an error

string was not in a correct value.

this is my code:

foreach (DataGridViewRow rw in dgv_student_update.Rows)
{
    for (int i = 0; i < dgv_student_update.Rows.Count; i++)
    {
        if (Convert.ToInt32(rw.Cells[3].Value) == 4)
        {
            sc.archive_student(dgv_student_update.Rows[i].Cells[2].Value.ToString(),last_year + " - " + current_year,Convert.ToInt32(dgv_student_update.Rows[i].Cells[1].value));
        }
    }
}

can anyone help please?

Upvotes: 0

Views: 156

Answers (2)

Slai
Slai

Reputation: 22876

Try this

Func<DataGridViewRow, int, int> cellValue = (row, i) => { 
   int.TryParse(row.Cells[i].Value + "", out i); return i; }; // returns 0 if TryParse fails

foreach (DataGridViewRow rw in dgv_student_update.Rows)
    if (cellValue(rw, 3) == 4)
        sc.archive_student(rw.Cells[2].Value.ToString(), 
        last_year + " - " + current_year, cellValue(rw, 1));

Upvotes: 1

Crowcoder
Crowcoder

Reputation: 11514

It's just a matter of proper null and value checking. You cannot assume everything has a value and it is in the format you expect. First make sure the cell has a value. Then make sure the value can be converted to an integer. Follow this advice for your update as well, you are likely to hit the same kind of problem calling archive_student.

 for (int i = 0; i < dgv_student_update.Rows.Count; i++)
 {
     if(rw.Cells[3].Value != null)
     {
         string strCell3 = rw.Cells[3].Value.ToString();
         int intCell3 = 0;
         if(int.TryParse(strCell3, out intCell3))
         { 
            if (intCell3 == 4)
            {
                sc.archive_student(dgv_student_update.Rows[i].Cells[2].Value.ToString(),last_year + " - " + current_year,Convert.ToInt32(dgv_student_update.Rows[i].Cells[1].value));
            }       
         } 
         else
         {
            //you decide what to do if its not an integer value
         }  
     }  
     else
     {
         //you decide what to do if cell has no value
     }     
  }

Upvotes: 0

Related Questions