简体   繁体   中英

ASP.NET: Controls are null when I try to change a property

  1. Created a user control.
  2. Within user control, I have a simple control, like a Literal, in the markup.
  3. In the user control's Page_Load, I attempt to change a property, like Text, on control created in the markup.
  4. Control is null.

What in the world am I missing?









(Begin rant: I am doing all these fancy things with login systems and dynamically adding/modifying controls on the fly with AJAX, etc, but I can't change an f'n static control's property! I can't even Google such a simple problem without finding something else! In the past, I had to dynamically generate the whole bloody page to avoid this idiotically simple problem. End rant.)

I know this is an old one, but wanted to chime in on how I fixed a similar issue I was having. I have a usercontrol with an asp:Panel on it that I was trying to set the visibility off during the Page_Load, but the control was coming up null. I then noticed that my Page_Load definition looked like this:

protected void Page_Load(object sender, EventArgs e)
{
   _myControl.visible = true;
}

When in fact, I needed the definition to look like this:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    _myControl.visible = true;
}

Doing the override fixed the issue.

Page.LoadControl() has two overloads, one accepts a Virtual Path, the other accepts a Type. Sometimes, when using the Type version overload, you get this kind of behaviour.

When possible, try to use the Virtual Path version of LoadControl.

Edit: as an FYI, this is because the actual Type of a User Control is not what you would expect it to be. ASP.NET kind of 'wraps' the Type of the User Control.

I figured out a way after analyzing the order a page is executed ( http://msdn.microsoft.com/en-us/library/ms178472.aspx ).

protected void Page_Init(object sender, EventArgs e)
{
   literalGameName.Text = myGame.Name;
}

Init happens after controls have been made, but not after the page is done loading control-stuff.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM