Reputation: 103
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" />
Upvotes: 0
Views: 2114
Reputation: 103
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)
Upvotes: 2