2
votes

I am having textboxes and buttons in 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. 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:

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

Please help me out of this.

2
Please have a look at this website they have a sample very similar to what you try to achieve. aspsnippets.com/Articles/…Ricky Stam

2 Answers

4
votes

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

Basicly this is an example of how to get the TextBox value:

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