How ugly is this solution?
I guess this can be called an anti-pattern, but it sort of works if you have a really small solution and no other coders than yourself :)
Imagine having a web form, which has a label control on it and this web form also loads a user control during run-time. The user control has a single button on it and when pressed, the button should set the text value of the label to the current date and time.
Now, there are some good ways and some bad ways to send data from a child control to a parent control, and I usually use events for this. Another way of doing this would be to access a property in the parent directly from the child control, but personally I think this is a really ugly way of doing things. How ugly do you think this is?
In the web form, add a public property to be able to set the label text:
protected System.Web.UI.WebControls.Panel Panel1;
protected System.Web.UI.WebControls.Label Label1;
private string mylabel = null;
public string Mylabel
{
get { return mylabel; }
set
{
mylabel = value;
this.Label1.Text = mylabel;
}
}
In the user control, the Page property of the control (which always points at the parent page, not the parent control) into the correct WebForm class, then set the public label property we define above directly.
private void Button1_Click(object sender, System.EventArgs e)
{
if(this.Page is WebForm1)
{
WebForm1 form = (WebForm1)this.Page;
form.Mylabel = "Time is " + DateTime.Now;
}
}