Friday, August 2, 2013

How to add a control to user control from a web page in asp.net

This post in a reply to a question on stackoverflow.com. Where the person who asked this question want to add control from the asp.net page dynamically. I decided to write a blog post here.

So let’s first create a user control for this.

MyUserControl

After creating a user control It’s try to put the user control in the aspx page like following.



<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<%@ Register Src="~/MyUserControl.ascx" TagPrefix="uc1" TagName="MyUserControl" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <uc1:MyUserControl runat="server" id="MyUserControl" />
    </div>
    </form>
</body>
</html>

So now our user control and ASP.NET Page ready. I am going add a textbox dynamically to user control in page_load event of web page like  following.

using System;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                TextBox textbox=new TextBox {ID = "myTextBox"};
                MyUserControl.Controls.Add(textbox);
            }
        }
    }
}

That’s it. When you run this application in browser it will look like following.

Add usre control dynamically in asp.net page with user control

That’s it. hope you like it. Stay tuned for more..
Share:

2 comments:

Your feedback is very important to me. Please provide your feedback via putting comments.

Search This Blog
About Me
My Photo

Full Stack Developer,Blogger,Microsoft Mvp, Mentor, Life long learner, 10+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC,Web Forms,C#,AngularJs,Golang
Mvp profile
Subscribe to my blog

Enter your email address:

Follow us on facebook
Blog Archive
Total Pageviews