Reputation: 1213
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
Reputation: 460138
txt.Parent.Parent.Parent
use txt.NamingContainer
.ViewState
/Session
/Hiddenfield
to persist a value across postbacks.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