0
votes

Simple FindControl not working - kicking back:

System.NullReferenceException: Object reference not set to an instance of an object.

I've got an asp.net label on a web page.

<asp:Label ID="lblMenuItemName1" runat="server" Text="Label"></asp:Label>

The label control is not inside any other control (datagrid, repeater, etc). Calling the code on a button click.

Dim lblMenuItemName as Label
lblMenuItemName = CType(Page.FindControl("lblMenuItemName1"), Label)
lblMenuItemName.Text = "Hello"

I've also tried (and about a half dozen of scenarios):

lblMenuItemName = FindControl("lblMenuItemName1")
lblMenuItemName = Me.FindControl("lblMenuItemName1")

I'm doing this, instead of referencing the control directly, because I've got ten of these labels and I'm going to assign text through a Loop using

FindControll("lblMenuItemName" & x.ToString)

FYI - referencing the control directly works fine.

 lblMenuItemName1.text = "Hello"

Where am I going wrong?

Update: I've discovered the problem (thanks to comments below) that my problem is that my control is in a Content control. Now looking to find out how to reference a label within a content control. Something like:

 Dim x As Content = Me.FindControl("Content3")
 Dim lblMenuItemName As Label = x.FindControl("lblMenuItemName1")
 lblMenuItemName.Text = "hello"


<asp:Content ID="Content3" ContentPlaceHolderID="ContentBody" Runat="Server">
<asp:Label ID="lblMenuItemName1" runat="server" Text="Label"></asp:Label><br /><br />
<asp:Button ID="Button1" runat="server" Text="Button" />

1
Try doing a recursive find and spitting out the parent where it's found and see if that sheds some light? Also if these are created dynamically they won't be available in a postback, in case that's an unstated part of the problem. - MrGadget
Can you post your page that would help? - zaggler
In putting a sample page together for Zaggler I discovered what I believe to be my problem. The label control is actually in a Content control: <asp:Content ID="Content3" ContentPlaceHolderID="ContentBody" Runat="Server"></asp:Content> What is is correct way to findcontrol inside the content control? - user1375002
See my other comment...I figured this would be the case. - MrGadget

1 Answers

1
votes

After several hours and dozens of trial and error, here is what I was looking for:

    Dim lblMenuItemName As Label = TryCast(Master.FindControl("ContentBody").FindControl("lblMenuItemName1"), Label)