Search code examples
c#asp.netgridviewtemplatefield

Updating Textbox in a templateField with button


it's my first time asking a question here in stackoverflow so please bear with me. I am creating a webpage using asp.net, I have GridView with columns set as databound except 1 template field, within the template field is a textbox and a button. I want to update the value of the textbox using an outside button(a button in the same page, but outside the gridview), can anyone show/tell me how to do that?

GridView1 is the ID of the gridView,

here is the templateField:

<asp:TemplateField HeaderText="Template Field1">
    <ItemTemplate>
         <asp:TextBox runat="server" ID="textboxs">
         </asp:TextBox>
         <asp:Button runat="server" ID="buttons" Text="S"/>
     </ItemTemplate>
     <HeaderStyle Width="15px" />
     <ItemStyle Wrap="False" />
</asp:TemplateField>

<asp:Button ID="Button1" runat="server" onclick="Button1_Click1" Text="Button" />

here is the Code Behind:

protected void Button1_Click1(object sender, EventArgs e)
{
    GridViewCode.Rows[0].Cells[10].Text = "Some Text";
}

I think the problem is that the templatefield has a textbox and a button, please correct me if I am wrong.

BTW I can't remove the button in the templatefield, it has to be a textbox with a button. Thanks.


Solution

  • protected void Button1_Click1(object sender, EventArgs e)
    {
        // First bind you grid again over here other wise it will lost data
    
        GridView1.DataSource = you List of Objects or DataTable;
        GridView1.DataBind();
    
        foreach (GridViewRow gvr in GridView1.Rows)
        {
            if (gvr.RowType == DataControlRowType.DataRow)
            {
                // to fill all text boxes
                TextBox textboxs = gvr.FindControl("textboxs") as TextBox;
                textboxs.Text = "You text";
    
    
                // to fill specific text box
                // use gvr.DataItem to check aging specific data item using if and then
                // textboxs.Text = "You text";
            }
        }
    }