Newbie Question - Refercing a User Control from a form

D

damiensawyer

Hi all,

I'm just starting out with user controls. Can someone please tell me
how I can reference the user control from the page which is hosting it?
Specifically, I wish to set a property on one of the objects of the
user control based on the state of an object in the hosting page.

I've created a control with runat=server. The other label control
appears in the 'overload controls' drop down list, but the UC doesn't.

<uc1:header id="Header1" runat="server"></uc1:header></P>
<asp:Label id="lblMessage" runat="server">Label</asp:Label></P>

Thanks very much in advance, any help would be greatly appreciated,




Damien Sawyer
 
W

William F. Robertson, Jr.

I am not sure what you mean by "overload controls" drop down list, but you
are probably missing a declaration on your code behind. Looking at your
snippet below you probably have this line defined at the top of your page
class:

protected System.Web.UI.WebControls.Label lblMessage;

You should add the UserControl to the page as well, assuming that your
"header" UserControl is called myUserControl.. Notice the name of the
variable is the same as the ID on the aspx page.

protected myUserControl Header1;

You should then be able to access Header1 anywhere in code and have access
to all the properties therein.

HTH,

bill
 
J

jhcorey

In your host page you may have to add:
Protected WithEvents Header1 As Header

Then you'll have access to the public properties of the user control.

HTH
Jim
 
P

Phillip Ian

In your user control, include a public property such as this:

Public Property LabelText() As String
Get
Return Label1.Text
End Get
Set(ByVal Value As String)
Label1.Text = Value
End Set
End Property

You can set the value either directly in your HTML:

<uc1:header id="Header1" LabelText="This is a test..."
runat="server"></uc1:header>

or in your codebehind's Page.Load handler:

Header1.LabelText = "This is a test..."

Note that if you're going to do it in codebehind, you'll need to
declare a variable Header1. Not really sure why this isn't done
automatically when you drag a UC onto a page, but it's not that tough.

Just drop "Public Header1 As header" after the auto generated stuff.
Make sure you use the same name as you give your UC, and of course, the
same class.

Hope this helps,

-Phil
 
D

damiensawyer

Thanks very much to all of you! I learnt a lot of great stuff from your
answers. I think that I'm finally getting the hang of this web
programming :)


DS
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,069
Latest member
SimplyleanKetoReviews

Latest Threads

Top