views:

33

answers:

3
  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.)

A: 

Instantiate user control by calling LoadControl method of the Page.

Igor
A: 

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.

Danny Drogt
A: 

Literally 30 seconds after I post my question, 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.

I'm just amazed that I couldn't find an answer to this on the web. I mean, this has to be the first mistake every noob ASP.NET coder has to run into if they have a Windows Forms background like me!

Thanks for the many responses and ignoring my rants. :-)

JKZ
Oh, and can someone vote this as the correct answer? (It says I have to wait two days to vote my own answer as the right answer! I guess we don't trust people to solve their own problems, eh? :-P)
JKZ