如何从gridview访问文本框文本到按钮Onclick事件

时间:2013-10-27 16:54:38

标签: c# asp.net button gridview

我在gridview中有文本框和按钮。我想要的是,当我点击这些按钮时,文本框中的相应值将更新为数据库,因此我需要访问OnClick事件中的文本框文本。我怎么能这样做?

的GridView:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            BackColor="#CCCCCC" BorderColor="#999999" 
            BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" 
            ForeColor="Black" OnRowDataBound="GridView1_RowDataBound" 
            onselectedindexchanged="GridView1_SelectedIndexChanged">
            <Columns>
                <asp:TemplateField HeaderText="Save 1">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox1" Width="30px" runat="server"></asp:TextBox>
                        <asp:Button ID="btnSave1" runat="server" Text="Save"  OnClick="btnSave1_Click" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Save 2">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox2" Width="30px" runat="server"></asp:TextBox>
                        <asp:Button ID="btnSave2" runat="server" Text="Save"  OnClick="btnSave2_Click" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
</asp:GridView>

按钮Onclick事件:

protected void btnSave1_Click(object sender, EventArgs e)
    {
         //I want to access TextBox1 here.
    }

请帮我解决这个问题。

2 个答案:

答案 0 :(得分:4)

你可以这样做:

protected void btnSave1_Click(object sender, EventArgs e)
{
     GridViewRow row = (GridViewRow)((Button)sender).NamingContainer;
     TextBox TextBox1 = row.FindControl("TextBox1") as TextBox; 

      //Access TextBox1 here.
      string myString = TextBox1.Text;
}

答案 1 :(得分:0)

基本上这是一个如何获取TextBox值的示例:

string CustomerID = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCustomerID")).Text;