在gridview中更新数据

时间:2012-01-12 21:19:19

标签: c# asp.net

我在VS 2005中有一个gridview。网格显示在文本框中,因此用户可以编辑。

  <asp:TemplateField ItemStyle-Width="50">
      <ItemTemplate>
          <asp:TextBox ID="txtSmall" runat="server" Width="45px" Text='<%#DataBinder.Eval(Container.DataItem,"Small") %>' OnTextChanged="TxtSmallChanged"> </asp:TextBox>                                                          
      </ItemTemplate>
  </asp:TemplateField>
  <asp:TemplateField ItemStyle-Width="50">
       <ItemTemplate>
            <asp:TextBox ID="txtMedium" runat="server" Width="45px" Text='<%#DataBinder.Eval(Container.DataItem,"Medium") %>' OnTextChanged="TxtMediumChanged"> </asp:TextBox>                                                          
        </ItemTemplate>
    </asp:TemplateField>
 <asp:TemplateField ItemStyle-Width = "50">
       <ItemTemplate>
             <asp:TextBox ID="txtTotal" runat="server" Width="45px" Text='<%#DataBinder.Eval(Container.DataItem,"Total") %>'> </asp:TextBox>
             </ItemTemplate>                                                     
       </asp:TemplateField>

每当文本框txtsmall或txtmedium更改(数字)时,textbox txttotal必须更新为txtSmall和txtmedium中的两者的总和。当我的文本被更改时,我正在使用函数TxtSmallChanged。如何编写codebehind函数来更新txtTotal。我希望我很清楚。非常感谢你!!

1 个答案:

答案 0 :(得分:0)

试试这个:
设置Autopostback = true

 protected void txtSmall_TextChanged(object sender, EventArgs e)
    {
        TextBox t = (TextBox)sender;
        GridViewRow r = (GridViewRow)t.NamingContainer;
        Txtchanged(r.RowIndex);
    }

    protected void txtMedium_TextChanged(object sender, EventArgs e)
    {
        TextBox t = (TextBox)sender;
        GridViewRow r = (GridViewRow)t.NamingContainer;
        Txtchanged(r.RowIndex);
    }

    private void Txtchanged(int row_index)
    {
        TextBox t1 = (TextBox)GridView1.Rows[row_index].Cells[0].FindControl("txtSmall");
        TextBox t2 = (TextBox)GridView1.Rows[row_index].Cells[0].FindControl("txtMedium");
        TextBox t3 = (TextBox)GridView1.Rows[row_index].Cells[0].FindControl("txtTotal");
        t3.Text = (Convert.ToInt32(t1.Text) + Convert.ToInt32(t2.Text)).ToString();

    }

您可以使用Txtchanged中的新值更新数据库