Answers
May 31, 2007 - 02:29 PM
First, let me tell you, that what you want to do is not good design. You tie the user control to the parent and are dependent that there is a method or property on the parent! This creates dependencies which should be avoided. It would be the same as if a Button control is using a property on the form. You would only be able to add Button controls to forms which have this property!
Anyway, here is a solution:
I have a form which has a textbox named Textbox1. I create a Web User Control, which has a button and a label. If you click the button, the web user control gets the text of textbox1 from the parent control and sets the label's text to this text.
The code is:
protected void Button1_Click(object sender, EventArgs e)
{
TextBox tb = (TextBox) this.Parent.FindControl("TextBox1");
if(tb != null)
{
Label1.Text = tb.Text;
}
else
{
Label1.Text = "TextBox1 doesn't exist in parent container!"
}
}
This only lets you access a public property on the parent form!!!
The way you should do this (and a good design!) is, you should add an event to your web user control and handle the event on the parent form. Lets say you want to update an address after a user entered his/her address details in your web user control. The method which updates the database is on the parent form. You fire an event i.e. AddressUpdated Event from the web user form and handle this event on the parent page. The eventhandler initiates the update on the database. If you need to read a return value from this update, you should put it in a public property of the parent page and read this property in the web user control.
Does this make sense?
Cheers
Peter
Mar 04, 2009 - 07:44 AM
The Quomon Team
Nov 11, 2009 - 08:57 PM
Add New Comment