Ramin Asadi Ramin Asadi - 1 year ago 216
ASP.NET (C#) Question

return null textbox text in templateField inside of gridview

could not access textbox text in TemplateField


<asp:TemplateField HeaderText="PIN" AccessibleHeaderText="PIN">
<asp:TextBox ID="txtPin" runat="server" Width="50px" MaxLength="4"></asp:TextBox>

code behind:

foreach (GridViewRow gr in grdPin.Rows)
TextBox lblDate = (TextBox)gr.Cells[0].FindControl("txtPin");
string x = lblDate.Text;

variable x is null.

Answer Source

With TemplateFields you have to use FindControl on the GridViewRow not the cell:

TextBox txtPin= (TextBox)gr.FindControl("txtPin");

You always have to use FindControl on the NamingContainer of the control you want to find. If the control is in a GridViewRow then that is it's NamingContainer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download