Pages

Thursday, July 21, 2011

Load User Controls Dynamically in ASP.Net

Views

To dynamically create an instance of User Control we have to use Page.LoadControl () method which returns an instance of the Control class. And also the PlaceHolder control which acts as a container of controls.
Below is the code to show all the User Controls present in Application’s UserControls folder
in a single web page.
First of all we have to add a PlaceHolder control.
<asp:PlaceHolder ID=”PlaceHolder1″ runat=”server”></asp:PlaceHolder>
.
//UserControls is the folder which contains all the user controls used by the application.
const string userControlFolder = “~/UserControls”;
protected void Page_Load(object sender, EventArgs e
{
        ArrayList oArrayList = GetControlPaths();
        foreach (string path in oArrayList)
        {
            Control oControl = Page.LoadControl(path);
            PlaceHolder1.Controls.Add(oControl);
        }
    }
     // This method returns an ArrayList which holds the virtual path of all the User Controls.
    private ArrayList GetControlPaths()
    {
        ArrayList userControlPath = new ArrayList();
 //This string array contains only the list of files having .ascx extension which is the extension for user control
string[] files = Directory.GetFiles(MapPath(userControlFolder), “*.ascx”);
       foreach (string oFile in files)
       {
userControlPath.Add(Path.Combine(userControlFolder, Path.GetFileName(oFile)));
       }
        return userControlPath;
    }

0 comments:

Post a Comment

 

Web Design Company karimnagar, Web Designing warangal, Logo Design Company nizamabad, Indian Website Design Company, maddysoft.co.in