Accessing a control from another page

E

eagle

How do I access a control, like a placeholder, from another page, or another
user control that may be on the same page.

For instance, I have a web page with 2 user controls. One user controls
contains a placeholder to that will contain any error messages to be
displayed. If the first user control creates an error, I want to be able to
push that error to the 2nd control to display it at the placeholder.

I have tried
Dim ctrlError as new ucErrors
Dim lbl as new label
lbl.text = "Error has occurred"
ctrlError.ph.Controls.Add(lbl)

But I get an error saying "System.NullReferenceException: Object reference
not set to an instance of an object."
 
H

HoustonFreeways

I'm no expert in the subject, but I don't know of a way to get two user
controls to talk to each other directly.

One way to empower communication is indirectly through the parent page. For
example, you may have two user controls on a page, uc1 and uc2. If uc1 has
an error, have it create and event which will be received by the parent and
acted on by an event handler in the parent. The parent will have a direct
reference to uc2, so you can then set properties or do whatever you want
with uc2 in the event handler.

Also, your code snippet looks like you are trying to dynamically create an
instance of a user control. I've always done this using the loadcontrol
call, for example
Dim questionDisplayCtrl As Control =
LoadControl("../templates/questionListItemOptions.ascx")

What you are trying to do (Dim ctrlError as new ucErrors) looks more
suitable for a regular web server control, class, or a composite control.
 
J

Josh Mitts

Yes, that's right. You have to go through the parent page because the two
controls don't know anything about each other.

However, you shouldn't need to create a new instance of the control in your
code, because the parent page should automatically create it when it loads
up the .aspx file and sees the @Control directive, <uc:Control> tag, etc. So
the best way to access the control is to use the parent page's Page.Controls
property. Here's an example...this is terrible VB but you'll get the idea
;-)

' Assuming we are in the first user control

Dim ctrlErrorId
ctrlErrorId = "MyUserControl" ' need a variable for the user control ID,
otherwise how does it know which one to find?

Dim ctrlError as ucErrors
ctrlError = Parent.FindControl(ctrlErrorId)
' ctrlError now contains a reference to the error control

Hope that helps!
 

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,819
Latest member
masterdaster

Latest Threads

Top