使用 rowdatabound 在列之间求和

Sum between columns using rowdatabound

你好,我有 table 7 列,我想将第 3 列、第 4 列和第 5 列求和到第 6 列(总计) 但它总是得到这个错误 "Input string was not in a correct format"。 同样在值中注意它会是一些空值 thx

数据类型为浮点型

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

不要将单元格中的 .Text 用于任何其他字符串。如果要在 RowDataBound 事件中添加值,请使用 DataRowView 对象。从那里您可以获取值并使用它们。

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