检查datagrdiview单元格值的数值?

时间:2016-07-08 11:58:25

标签: c#

在我的项目中,我有一些带有一些列的datagridview,其中一列有一个数值。我想检查这个单元格值,但它给了我一个错误

  

字符串的值不正确。

这是我的代码:

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

任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

试试这个

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

答案 1 :(得分:0)

这只是适当的空值和值检查的问题。您不能假设所有内容都具有值,并且它采用您期望的格式。首先确保单元格有值。然后确保该值可以转换为整数。请按照此建议进行更新,您可能会遇到调用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
     }     
  }