asp.netsumrowdatabound

Sum between columns using rowdatabound


hello i have table with 7 columns i want to sum col number 3 and 4 and 5 to col 6 (total) but its always get this error "Input string was not in a correct format". also in the value make attention it will be some null value thx

datatype is float

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string val1 = e.Row.Cells[3].Text; //Gets the value in Column 1
        string val2 = e.Row.Cells[4].Text; //Gets the value in Column 2
        string val3 = e.Row.Cells[5].Text; //Gets the value in Column 2
        Label lblTotal = (Label)e.Row.Cells[6].FindControl("Label1"); //

        if (string.IsNullOrEmpty(val1))
        { val1 = "0"; }
        if (string.IsNullOrEmpty(val2))
        { val2 = "0"; }
        if (string.IsNullOrEmpty(val3) )
        { val3 = "0"; }


        int sum = Int32.Parse(val1) + Int32.Parse(val2) + Int32.Parse(val3);
        lblTotal.Text += sum.ToString();
    }
}

Solution

  • Don't use the .Text from the cells for anything else that strings. If you want to add values in the RowDataBound event, use the DataRowView object. From there you can get the values and use them.

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //check if the row is a datarow
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //cast the current row back to a datarowview
            DataRowView row = e.Row.DataItem as DataRowView;
    
            //get the values from the datarowview
            decimal val1 = Convert.ToDecimal(row["val1"]);
            decimal val2 = Convert.ToDecimal(row["val2"]);
            decimal val3 = Convert.ToDecimal(row["val3"]);
    
            decimal sum = val1 + val2 + val3;
    
            //find the label in the row with findcontrol
            Label lblTotal = e.Row.FindControl("Label1") as Label;
    
            //set the total value in the label with 2 decimal points
            lblTotal.Text = string.Format("{0:N2}", sum);
        }
    }