Can't access the server control from .cs code!

D

Davíð Þórisson

Trying to migrate from ASP... been scratching my head for almost 12 hours
now on this task that should be so easy, wtf can't I access the asp:label
control from my .cs code??? It returns no errors but simply no text is
inserted...
I have 3 pages;

*** default.aspx ***
<%@ Register TagPrefix="UserControls" TagName="Initializer"
Src="initializer.ascx" %>
<UserControls:Initializer runat="server" />

*** initializer.ascx ***
<%@ Control Src="initializer.cs" EnableViewState="False" %>
<asp:label id="myLabel" text="here I want the text" runat=server/>

*** initializer.cs ***
using System.Web.UI.WebControls;
public class Initializer
{
protected Label myLabel;
void Page_Load(object sender, System.EventArgs e)
{
Label myLabel = new Label();
myLabel.Text = "and I have success";
}
}
 
D

Derek Harmon

Davíð Þórisson said:
now on this task that should be so easy, wtf can't I access the asp:label
control from my .cs code??? : :
protected Label myLabel;

This is your user control's protected field, myLabel, of type Label.
void Page_Load(object sender, System.EventArgs e)
{
Label myLabel = new Label( );

This is a local variable in the Page_Load method, named myLabel, that is
covering up the myLabel private field.
myLabel.Text = "and I have success";

This line takes effect, but then this local variable leaves scope at the end
of the Page_Load method and in all this time, nothing has happened to
this.myLabel.Text.

Instead of declaring locally,

Label myLabel = new Label( );

just instantiate the Label you've already got,

myLabel = new Label( );

or, to be more explicit that you want the myLabel field on this user control,

this.myLabel = new Label( );


Derek Harmon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,820
Latest member
GilbertoA5

Latest Threads

Top