简体   繁体   English

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

[英]How to access a textbox text from gridview to a button Onclick event

I am having textboxes and buttons in gridview. 我在gridview中有文本框和按钮。 What I want is that when I click on those buttons the corresponding value in textbox is updated to database, so I need to access the textbox text in OnClick event. 我想要的是,当我单击这些按钮时,文本框中的相应值将更新为数据库,因此我需要在OnClick事件中访问文本框的文本。 How can I do this? 我怎样才能做到这一点?

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>

Button Onclick Event: 按钮Onclick事件:

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

Please help me out of this. 请帮助我。

You can do like this: 您可以这样:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM