Software Technology Tips

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;
    }


Related Tags:

ASP.NET

Author: Manaswinee Mohapatra

ASP.NET

Let us Connect!

privacy
iso 9001 QA25 Nasscom Red Herring zinnov STPI iso 27001

copyright (c) Mindfire Solutions 2007-2013. Login