Ahmad Rezaye
Ahmad Rezaye

Reputation: 57

pass textbox value to gridview

i have gridview control and textbox + button control in page aspx.

i want pass textbox value to gridview by click button.

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

and use this code:

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

but its no ok. :-( please help me.

Upvotes: 1

Views: 4305

Answers (2)

Adil
Adil

Reputation: 148110

If grid row has label with id lblName then you will get it from row and you do not need to check it again.

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

Note: If you do not have rows already in thr gridview then you wont be able get the value in label. You need to ensure their are row(s) in grid.

Upvotes: 1

MahaSwetha
MahaSwetha

Reputation: 1066

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

Upvotes: 3

Related Questions