Skip to main content
 首页 » 编程设计

c#之将文本框值传递给 gridview

2024年02月20日27luoye11

我在 aspx 页面中有 gridview 控件和文本框 + 按钮控件。

我想通过单击按钮将文本框值传递给 gridview。

<asp:GridView ID="gvName" runat="server" ViewStateMode="Enabled"> 
<Columns> 
<asp:TemplateField> 
<ItemTemplate> 
<asp:Label ID="lblName" runat="server"></asp:Label> 
</ItemTemplate> 
</asp:TemplateField> 
</Columns> 
</asp:GridView> 

并使用这段代码:

protected void btnAddName_Click(object sender, ImageClickEventArgs e) 
    { 
      foreach (GridViewRow row in gvName.Rows) 
        { 
            if ((Label)row.FindControl("lblName") is Label) 
            { 
                ((Label)row.FindControl("lblName")).Text = txtName.Text; 
            } 
        } 
     } 

但是不行。 :-( 请帮助我。

请您参考如下方法:

Create a rowdatabound command and place the below code.  
 
protected void gvName_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
        if (e.Row.RowType == DataControlRowType.DataRow) 
        { 
            Label lblName = (Label)row.FindControl("lblName");          
            lblName.Text = txtName.Text;   
        } 
}