Control Manager Concept
In many web applications there is a need to mark the control visible and invisible. Most of the time we end up doing the following.
private void ShowPanel()
{
myPanel.Visible = true;
myPanel.DataBind();
}
Although it will work just fine but what if we need to make the panel invisible on a different page. We will copy and paste the code in the page and thus the ugly process of duplicate code starts.
One idea is to make a base page which will contain all the useful functions needed by other pages. Something like the following:
public class BasePage: System.Web.UI.Page
{
protected void ShowPanel(Panel p)
{
p.Visible = true;
p.DataBind();
}
}
This will work fine but what about other controls which are not panel maybe a textbox or GridView. You can make it generic by using the Control type as a parameter.
protected void ShowControl(Control control)
{
control.Visible = true;
control.DataBind();
}
Now, you can pass in Panel, DataGrid, GridView, TextBox etc. But still there is one thing missing. What about if the panel or GridView is not in a page but in a User control. Offcourse, you can do the casting and get the UserControl on the page using the following code:
// Method 1
MyControl uc = Page.FindControl("MyControl1") as MyControl;
if (uc == null) return;
Panel ucPanel = uc.FindControl("userControlPanel") as Panel;
MakeInvisible(ucPanel);
// Method 2: MyControl has a public property UserControlPanel which returns the Panel control.
MyControl uc = Page.FindControl("MyControl1") as MyControl;
if (uc == null) return;
MakeInvisible(uc.UserControlPanel);
But, I think the best way is to create a ControlManager which can be responsible for performing all these tasks. These tasks can include making controls visible/invisible, populating dropdownlists etc.
Let me know what you think!