living for code living for code - 7 months ago 26
SQL Question

Getting sum of an unbound data column in asp.net Gridview

I am trying to get the sum of an unbound data column. Basically I have a gridview with dropdown list and an Amount column. I select quantity from that list and the price is multiplied with the quantity and the amount is shown in the "Amount" column. The Price is fetched from the database and itemID also. Now I want to sum up all the values in the "Amount" column. As I run this code, every row is updated successfully with the quantity and price multiplication but the total amount logic is adding the item_price + any value in the "amount" column. I only want the data to be added in the "Amount" column. I have a label in the bottom of the grid view where I am trying to get the total result value. HELP!!

The aspx file is like this:

<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server"
OnRowDataBound="GridView1_RowDataBound" ShowFooter="true">
<footerstyle backcolor="LightCyan"
forecolor="MediumBlue"/>
<Columns>
<asp:BoundField DataField="item_ID" HeaderText="ID" />
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:DropDownList ID="ddlQuantity" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlQuantity_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="purchase_price">
<ItemTemplate>
<asp:Label ID="lblPrice" Text='<%#Eval("purchase_price") %>' runat="server" ></asp:Label>
</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:Label ID="lblAmount" Text="0.00" runat="server" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>

</Columns>




Here is the code behind:

protected void ddlQuantity_SelectedIndexChanged(object sender, EventArgs e)
{
int quantity;
GridViewRow gvr = ((DropDownList)sender).NamingContainer as GridViewRow;
var ddlQuantity = gvr.FindControl("ddlQuantity") as DropDownList;
var lblAmount = gvr.FindControl("lblAmount") as Label;
var lblPrice = gvr.FindControl("lblPrice") as Label;
int.TryParse(ddlQuantity.SelectedValue, out quantity);
//Label1.Text = quantity.ToString();

int pr = int.Parse(lblPrice.Text);
int qt = int.Parse(ddlQuantity.SelectedValue);

//Label2.Text += (pr*qt).ToString();


lblAmount.Text = (pr * qt).ToString();

int sum = 0;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
sum += int.Parse(lblAmount.Text);
}
Label2.Text = sum.ToString();
}

Answer

You were pretty close. In your sum loop, you are only adding the same amount each time. Within that loop, you need to look up each lblAmount (for that row) and sum each one.

Try this code for your loop:

int sum = 0;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
    gvr = GridView1.Rows[i] as GridViewRow;
    var lblRowAmount = gvr.FindControl("lblAmount") as Label;

    sum += int.Parse(lblRowAmount.Text);
}
Label2.Text = sum.ToString();