页脚总网格视图TextChangedEvent

本文关键字:视图 TextChangedEvent 网格 | 更新日期: 2023-09-27 18:29:28

我在Gridview控件中有一个Textbox。当我在Textbox上输入金额时,我必须在Gridview页脚上显示。

,我试过这个

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();
    }

它是有效的,但问题是当一次又一次地更改相同的文本框值时。文本框值与总计相加。如何解决此问题?

页脚总网格视图TextChangedEvent

  1. 使用txt.NamingContainer代替txt.Parent.Parent.Parent
  2. 其次,不要在ASP.NET中使用静态字段。这在所有请求之间共享。相反,使用ViewState/Session/Hiddenfield在回发之间持久化值
  3. 如果你不想它被求和,那么就不要在回发后将其持久化,只需重新计算:

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));

如果您不能使用LINQ,或者TextBoxes可能为空或包含其他无效格式,请使用纯循环:

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;
}