使用按钮更新templateField中的文本框

时间:2013-12-05 09:46:47

标签: c# asp.net gridview templatefield

这是我第一次在stackoverflow中提问,所以请耐心等待。我正在使用asp.net创建一个网页,我有GridView,列设置为数据绑定,除了1个模板字段,模板字段内是一个文本框和一个按钮。我想使用外部按钮(同一页面中的按钮,但在gridview之外)更新文本框的值,任何人都可以显示/告诉我该怎么做?

GridView1是gridView的ID,

这是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" />

这里是Code Behind:

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

我认为问题是templatefield有一个文本框和一个按钮,如果我错了,请纠正我。

BTW我无法删除模板字段中的按钮,它必须是带按钮的文本框。感谢。

3 个答案:

答案 0 :(得分:1)

如果没有您的进一步代码,可以采用以下方式:

protected void Button1_Click1(object sender, EventArgs e)
{
   TextBox textboxs = GridView.Rows[2].FindControl("textboxs");
   textboxs.Text = "New Text Here";
}

其中index 2是gridview的数据绑定数据的行索引

答案 1 :(得分:1)

You can use a code like this:

    for (int i = 0; i < GridView.Rows.Count; i++)
    {
        GridViewRow gvr = GridView.Rows[i];
        Textbox txtBox= (Textbox)gvr.Cells[0].FindControl("textbox_id");
        txtBox.Text = "Your new text here";
    }

这将替换每行的文本框,您可以强制条件在特定行中替换它。

答案 2 :(得分:0)

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";
        }
    }
}
相关问题