Search code examples
c#asp.netgridviewrowcomputation

Input string was not in a correct format in gridview computation of cells


I tried to do the computation in this link but it says that input string was not in a correct format. I am computing values of cells in the gridview. Here is my code:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    int tot = 0;
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
          decimal medjtot = (Convert.ToInt32(e.Row.Cells[3].Text) * (Convert.ToDecimal(e.Row.Cells[4].Text) / 12)) * Convert.ToDecimal(e.Row.Cells[5].Text);
          Label RowTotal = (Label)e.Row.FindControl("Label1");
          RowTotal.Text = medjtot.ToString();    
    }
 }

Solution

  • Make sure you do a guard check on your Text property for each Row Cell. It is possible that the text is whitespace or empty.

    Sample guard check.

       if(string.IsNullOrWhiteSpace(e.Row.Cells[5].Text) || 
           string.IsNullOrWhiteSpace(e.Row.Cells[3].Text))
              return;