Monday, June 14, 2010

How to load UserControl with parameters. LoadControl("VirtualPath", p1, p2) - Asp.net

This article demonstrate how to load a user control with constructor parameters in the LoadControl method. However we have implemented a method which accepts VirtualPath and n number of parameters.

Please review example below:

<%@ Page Language="C#" %>
<html>
<head id="Head1" runat="server">
    <script runat="server">
        public UserControl LoadControl(string UserControlPath, 
                params object[] constructorParameters)
        {
            List<Type> constParamTypes = new List<Type>();
            foreach (object constParam in constructorParameters)
                constParamTypes.Add(constParam.GetType());
            UserControl ctl = Page.LoadControl(UserControlPath) as UserControl;
            ConstructorInfo constructor = ctl.GetType()
                .BaseType.GetConstructor(constParamTypes.ToArray());
            if (constructor == null)
                throw new MemberAccessException("The requested constructor was not found on : " 
                    + ctl.GetType().BaseType.ToString());
            else
                constructor.Invoke(ctl, constructorParameters);
            return ctl;
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            List<Employee> employees = new List<Employee>();
            if (!this.IsPostBack)
                for (int i = 0; i < 10; i++)
                    employees.Add(new Employee() { Id = "Emp" + i, Name = "Employee" + i });
            List<object> parameters = new List<object>();
            this.phUserControl.Controls.Add(this.LoadControl("~/UserControls/ActiveUserControl.ascx", 
                employees, "Existing Employees"));
        }
        protected override void OnLoad(EventArgs e)
        {
            this.EnsureChildControls();
            base.OnLoad(e);
            if (!this.IsPostBack)
                this.phUserControl.DataBind();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:PlaceHolder runat="server" ID="phUserControl"></asp:PlaceHolder>
    </form>
</body>
</html>

User Control

Markup:

<%@ Control Language="C#" AutoEventWireup="true" 
    CodeBehind="ActiveUserControl.ascx.cs" 
    Inherits="ActiveTest.UserControls.ActiveUserControl" %>
<div>
    <h1><asp:Label runat="server" ID="lblTitle" /></h1>
    <hr />
    <asp:GridView runat="server" ID="grvEmployees" AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Label runat="server" ID="lblId" Text='<%# Eval("Id") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:TextBox runat="server" ID="txtName" Text='<%# Eval("Name") %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

Code:

namespace ActiveTest.UserControls
{
    [ParseChildren(true)]
    public partial class ActiveUserControl : UserControl
    {
        public List<Employee> Employees
        {
            get { return (List<Employee>)(ViewState["Employees"] ?? (ViewState["Employees"] = new List<Employee>())); }
            set { ViewState["Employees"] = value; }
        }
        public string Title { getset; }
        public ActiveUserControl() { }
        public ActiveUserControl(List<Employee> employees, string title)
        {
            this.Employees = employees;
            this.Title = title;
        }
        public override void DataBind()
        {
            this.lblTitle.Text = this.Title;
            this.grvEmployees.DataSource = this.Employees;
            this.grvEmployees.DataBind();
        }
    }
 
    [Serializable]
    public class Employee
    {
        public string Id { getset; }
        public string Name { getset; }
    }
}

No comments:

iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...