I have a field ‘x’ on the user control form which is included on aspx page and that page using SharePoint master page. I’m trying to locate field x on aspx page in my code but it throws “Object ref not set” error. I’ve tried following but nothing works ,
((TextBox)Page.Master.FindControl("PlaceHolderMain").FindControl("Experience").FindControl("x")).Text
((TextBox)this.FindControl("x")).Text
((TextBox)Page.Master.FindControl("PlaceHolderMain").FindControl("x")).Text
I can locate the field on page source,
<input name="ctl00$PlaceHolderMain$ctl00$x" type="text" value="3" id="ctl00_PlaceHolderMain_ctl00_x" class="textbox" />
Update:-
Previously I was adding user control programmatically on load event of the aspx page,
UserControl uc = (UserControl)Page.LoadControl("Experience.ascx");
experineceForm.Controls.Add(uc);
But by seeing page source I had doubt and thought to add it in design time using following code,
<%@ Register TagPrefix="uc" TagName="Experience" Src="Experience.ascx" %>
<div id="experineceForm" runat="server">
<uc:experience id="idExperienceForm" runat="server"/>
</div>
After doing this I’m able to find controls with following code,
((TextBox)Page.Master.FindControl("PlaceHolderMain").FindControl("idExperienceForm").FindControl("txtEmployeeComments")).Text
Try this function (below) to do a recursive search for the ID. Most probably the System.NullReferenceException: Object reference not set to an instance of an object error is because the script did not find the text box so the control did not have a
.Textproperty. NB: root would be the id of an asp.net placeholder object or an asp.net panel, etc. that contains the text box you are looking for. You should test for null returns before attempting to use the control.