Aayushi Jain
Aayushi Jain

Reputation: 2879

How to access a textbox text from gridview to a button Onclick event

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.

Upvotes: 3

Views: 12462

Answers (2)

afzalulh
afzalulh

Reputation: 7943

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

Upvotes: 5

Ricky Stam
Ricky Stam

Reputation: 2126

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

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

Upvotes: 0

Related Questions