Rob Webs
Rob Webs

Reputation: 5

How to sum a column in GridView then display to label in ASP.Net?

I have been looking for the solution for this problem but most of them does not fix it or I don't understand. This is my attempt trying to sum up the whole single column:

protected void Page_Load(object sender, EventArgs e)
{
    GridView1.DataSource = SqlDataSource1;
    GridView1.DataBind();

        int sum = 0;
        for (int i = 0; i <GridView1.Rows.Count; ++i)
        {
            sum += Convert.ToInt32(GridView1.Rows[i].Cells[4].Value);
        }
        Label_Grand.Text = sum.ToString();
    }
}

The error shows up at sum += Convert.ToInt32(GridView1.Rows[i].Cells[4].Value); the word Value.

'TableCell' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'TableCell' could be found (are you missing a using directive or an assembly reference?)

Upvotes: 0

Views: 1867

Answers (1)

haldo
haldo

Reputation: 16711

Use .Text instead. Also, based on your comments you have Money set in the database which should map to decimal in C#.

decimal sum = 0.0m;
for (int i = 0; i <GridView1.Rows.Count; ++i)
{
    sum += Convert.ToDecimal(GridView1.Rows[i].Cells[4].Text);
}

GridViewRow Cells do not have a Value property.

Upvotes: 1

Related Questions