Tuesday, September 20, 2011

How to pass parameters to ASP.NET user control

One common way of passing parameters to ASP.NET user control is to use public properties in user control. As always, let's take a look at a simple example here. The following user control displays main title with a specific style.

MainTitle.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MainTitle.ascx.cs" Inherits="MyWeb.Modules.MainTitle" %>
   
<div class="main-title">
  <asp:Label ID="lblTitle" runat="server" Text="Main" />
</div>
<br />

In .aspx page that includes this user control, one might want to change title text of this control. To pass title parameter, one public property called Title is added to user control code-behind file as follows.

MainTitle.ascx.cs
namespace MyWeb.Modules
{
   public partial class MainTitle : System.Web.UI.UserControl
   {
      protected void Page_Load(object sender, EventArgs e)
      {
          if (!string.IsNullOrEmpty(Title))
          {
              lblTitle.Text = Title;
          }          
      }

      public string Title { get; set; }
   }
}

Now, ASP.NET page containing the user control can pass parameter by setting any value to the public property of the ascx control. First, test.aspx file below registers the user control and add MainTitle user control to the web page.

Test.aspx
<%@ Page Language="C#" MasterPageFile="~/Masters/DefaultLayout.master" AutoEventWireup="true"
    CodeBehind="Test.aspx.cs" Inherits="Test.Article" %>
<%@ Register TagPrefix="myControl" TagName="MainTitle" Src="~/Modules/MainTitle.ascx" %>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="Main">
    <myControl:MainTitle runat="server" ID="mainTitle" />       
</asp:Content>

Then in the code-behind, Title property of the mainTitle object can be set as follows.

Test.aspx.cs
public partial class Test: System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    if (!this.IsPostBack)
    {                                
       mainTitle.Title = "New Title"; //set property              
    }
  }
}

1 comment:

  1. Hi,Back to web page design templates, consider the purpose for the templates before you jump on the internet and buy...are you using it for a Google AdSense page, or is it for a product or Web Design Cochin service you are selling, maybe it's just a simple home page for you and your family, whatever make sure you find the proper web page design templates to fit your needs.Thanks.....

    ReplyDelete