将文本框值传递给gridview

时间:2013-01-10 07:33:22

标签: c# asp.net gridview

我在页面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;
            }
        }
     }

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

如果网格行的标签带有id lblName,那么您将从行中获取它,而不需要再次检查它。

foreach (GridViewRow row in gvName.Rows)
{
    Label lblName = (Label)row.FindControl("lblName");         
    lblName.Text = txtName.Text;            
}

注意:如果您在thr gridview中没有行,那么您将无法获得标签中的值。您需要确保它们是网格中的行。

相关问题