Ramin Asadi Ramin Asadi - 3 months ago 24
ASP.NET (C#) Question

return null textbox text in templateField inside of gridview

could not access textbox text in TemplateField

.aspx:

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


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

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.

Comments