How to load user control dynamically in asp.net page ?


Hi

So many time we get scenario to display some user control on some location on some condition then we can achieve this by loading the user control dynamically.

For doing this task we can do like

Step 1: Create some list of user control and keep in some folder

Step2: Keep one place Holder control in asp.net page like this


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicLoadingUserControl.aspx.cs" Inherits="DynamicLoadingUserControl" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
    </div>
    </form>
</body>
</html>


Step 3: Now write the code behind file of aspx page for loading the user control like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class DynamicLoadingUserControl : System.Web.UI.Page
{
    // randomFolder is the Folder Name which Contains the collection of User control
    const string randomFolder = "TestUserControl";

    protected void Page_Load(object sender, EventArgs e)
    {
        string featuredProductPath = GetRandomProductPath();
        Control featuredProduct = Page.LoadControl(featuredProductPath);
        PlaceHolder1.Controls.Add(featuredProduct);
    }

    private string GetRandomProductPath()
    {
        Random rnd = new Random();
        string[] files = Directory.GetFiles(MapPath(randomFolder), "*.ascx");
        string featuredProductPath = Path.GetFileName(files[rnd.Next(files.Length)]);
        return Path.Combine(randomFolder, featuredProductPath);
    }
}

Advertisements

How to Fire event from UserControl to Parent aspx page ?


UserControlClick
Hi

This is one of the frequently used function of user control. For example you have created some user control and from user control you have to fire some event in parent asp.net page.

Then you have to expose event like this

Step 1: Create one simple User Control with one button control


<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Hello.ascx.cs" Inherits="Hello" %>

<asp:Button ID="btnClick" runat="server" Text="Click Here" 
    onclick="btnClick_Click" />


Step 2: Write code for exposing event like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Hello : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public event EventHandler BtnClick;

    protected void btnClick_Click(object sender, EventArgs e)
    {
        BtnClick(this, EventArgs.Empty);
    }
}

Step 3: Now create one aspx page and implement the usercontrol in this page like this


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Hello.aspx.cs" Inherits="Hello" %>
<%@ Register TagPrefix="user" TagName="HelloUserControl"  Src="~/Hello.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <user:HelloUserControl ID="usrControlTest" runat="server" OnBtnClick="usrControlTest_Click" /> <br /><br />

    <asp:Label ID="lblmsg" runat="server" />
    
    </div>
    </form>
</body> 
</html>


Step 4: write the code in code behind file like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Hello : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void usrControlTest_Click(object sender, EventArgs e)     
    {
        lblmsg.Text = "Hello User Control";
    }
}

Note : Here we are firing event from user control on button click event

I hope this will help to some one.

How to expose property from User Control ?


dynamic Image
Hi,

While working with user control in asp.net , you will get scenario to expose property from  user control to make it dynamic.

For example , you want to create user control to display random images on page refresh from some image folder. Now you want to make that Image folder path as dynamic then you have to expose property from user controls like this.

Step 1: Create the User Control Like this

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="PropertyTest.ascx.cs" Inherits="PropertyTest" %>

<asp:Image ID="imgRandom" Width="200px" Height="200px" runat="server" /> <br />
<asp:Label  ID="lblRandom" runat="server"></asp:Label>

Step2: Write the code behind file for UserControl like this

UserControl_Property

Step 3: Now implement the usercontrol in asp.net page and give the folder name of image like this code.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PropertyTest.aspx.cs" Inherits="PropertyTest" %>

<%@ Register TagPrefix="user" TagName="PropertUserControl" Src="~/PropertyTest.ascx" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

       <user:PropertUserControl ID="Test"  ImageFolderPath="Img" runat="server" />

    </div>
    </form>
</body>
</html>


Dynamic FolderName

What is the UserControl in asp.net ?


User control is like other control which can be designed on basis of our own requirement to avoid the repeating of same code in entire application.  It will increase the productivity and maintainability.

 For example, if we have to design same registration page in two module of application then we can create the user control for one registration page and we can reuse this user control in other page.

How to implement user control in asp.net web form page ?

Firstly you create the user controls like normal web form page, only page extension will be different i.e .ascx  

You can add the user control in your page by using Register page directive like this image.

Image

Note:

TagePrefix: Indicates the namespace that you want to associate with the usercontrol for the current page

TagName: Indicates the name that you want to associate with UserControl for current page.

Src:  Indicates the virtual path of user control.

 

 

 

 

 

How to select the Gridview rows data in asp.net ?


GrdSelect

Hi

It is very simple to do this functionality in asp.net

Step 1: Add the AutoGeneratedSelectButton=”true” in gridview like this

  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            AutoGenerateSelectButton="True"  
            DataSourceID="SqlDataSource1" 
            onselectedindexchanged="GridView1_SelectedIndexChanged1">

Step 2: Fire the event “SelectedIndexChanged” and write the code for selecting rows


protected void GridView1_SelectedIndexChanged1(object sender, EventArgs e)
    {
        string actualWt = GridView1.SelectedRow.Cells[2].Text;
        string amount = GridView1.SelectedRow.Cells[3].Text;
    }

How to hold the list of Data in Viewstate of asp.net ?


Hi

While working on one of personal project there was requirement to hold the collection of data of some event and again i have to validate that data on some other event, then i did using Viewstate like this sample code


 protected void Button1_Click(object sender, EventArgs e)
        {
            ViewStateList.Add(1);
            ViewStateList.Add(5);
        }
        protected List<int> ViewStateList
        {
            get
            {
                if (ViewState["Record"] == null) ViewState["Record"] = new List<int>();
                return (List<int>)ViewState["Record"];
            }
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            foreach (int n in ViewStateList)
            {
                Response.Write(n);
            }
        }

I hope this will help to somebody.

Posted in Asp.net. 1 Comment »