Janet
Janet

Reputation: 1411

Need the total of the footer in gridview in a textbox outside the gridview

I have a gridview with a footer and I display the total of the price column in the footer. I want to access the value in the footer and display it in the textbox which is outside the gridview.

This is how my gridview looks only the footer template

 <asp:TemplateField HeaderText="Total" >
<ItemTemplate>
<asp:Label ID="lbltotal" runat="server" Text='' ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lbltotalprice" runat="server" Text=''></asp:Label>
</FooterTemplate>
</asp:TemplateField>

Below is how i am displaying the total in the footer

In gridview rowdatabound event
    if (e.Row.RowType == DataControlRowType.Footer)
            {
                Label amounttotal = (Label)e.Row.FindControl("lbltotalprice");
                amounttotal.Text = String.Format("{0:C2}", total);
            }  

I tried it in the below way in another method

GridViewRow row = GridView1.FooterRow; 
Total.Text= ((Label)row.FindControl("lbltotalprice")).ToString();--- does not help at all

Please help in accessing this value in footer in a texbox outside of gridview. Thanks in advance.

Upvotes: 1

Views: 4637

Answers (3)

Mun
Mun

Reputation: 14308

You could try setting this outside of the ItemDataBound event, once your list has been bound and the item amounts have all been populated (so that you can retrieve these values and calculate the total). An example of how to do this is below:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        MyGrid.DataSource = GetDataSource();
        MyGrid.DataBind();

        SetTotalInGridFooter();
    }
}

private void SetTotalInGridFooter()
{
    double total = 0;

    foreach (RepeaterItem ri in in MyGrid.Items)
    {
        if (ri.ItemType == ListItemType.Item || ri.ItemType == ListItemType.AlternatingItem)
        {
            double d;

            Label lbltotal = (Label) ri.FindControl("lbltotal");

            if (Double.TryParse(lbltotal.Text, out d))
               total += d;

            continue;
        }

        if (ri.ItemType == ListItemType.Footer)
        {
            Label lbltotalprice = (Label) ri.FindControl("lbltotalprice");
            lbltotalprice.Text = String.Format("{0:C2}", total);

            break;
        }
    }
}

Upvotes: 2

Priyank
Priyank

Reputation: 10623

Use textbox instead of label try it. Textbox is accessible with same syntax but I have seen issues with label.

string a = ((TextBox)row.FindControl("TextBox1")).Text;

Upvotes: 1

JasonS
JasonS

Reputation: 23868

What about something like this:

if (e.Row.RowType == DataControlRowType.Footer)
{
     Label amounttotal = (Label)e.Row.FindControl("lbltotalprice");
     amounttotal.Text = String.Format("{0:C2}", total);
     Total.Text = amounttotal.Text;
}

Upvotes: 1

Related Questions