King_Fisher
King_Fisher

Reputation: 1213

Footer Total Gridview TextChangedEvent

I have Textbox with in the Gridview Control.when i enter amount on Textbox i have to show on Gridview Footer.

i have tried this,

static float total=0;

 protected void txtintroId_TextChanged(object sender, EventArgs e)
    {
    TextBox txt = (TextBox)sender;

    GridViewRow grid = ((GridViewRow)txt.Parent.Parent.Parent);

    TextBox txt1= (TextBox)txt.FindControl("txtbox");
     total=float.parse(txt1.Text);
    GridView1.FooterRow.Cells[4].Text = total.ToString();
    }

its working, but The problem is when Change the Same Textbox value again and again.the textbox value Add with Total. how do i Solve this ?

Upvotes: 0

Views: 402

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460138

  1. Instead of txt.Parent.Parent.Parent use txt.NamingContainer.
  2. Second, don't use a static field in ASP.NET. This is shared across all requests. Instead use ViewState/Session/Hiddenfield to persist a value across postbacks.
  3. if you don't want that it gets summed then don't persist it acoss postbacks, just recalculate it:

TextBox txt = (TextBox)sender;
float value = float.Parse(txt.Text);
GridViewRow row = (GridViewRow) txt.NamingContainer;
GridView gridView = (GridView) row.NamingContainer;
float total = gridView.Rows.Cast<GridViewRow>()
    .Sum(row => float.Parse(((TextBox) row.FindControl("txtbox")).Text));

If you can't use LINQ or the TextBoxes can be empty or contain other invalid formats use a plain loop:

float total = 0;
foreach (GridViewRow gridViewRow in gridView.Rows)
{
    txt = (TextBox) gridViewRow.FindControl("txtbox");
    float rowValue = 0;
    if (float.TryParse(txt.Text.Trim(), out rowValue))
        total += rowValue;
}

Upvotes: 2

Related Questions