Mental Jetsam

By Peter Finch

Archive for March, 2011

Simple ASP.NET User Control

Posted by pcfinch on March 1, 2011

This is a simple ASP.NET user control template that can be used with a data bound data source and has a persistent ViewState. The trick when using the control with something like a data bound DataList, etc,  is to initialize the value of the child controls (e.g. lblMessage) in the Page_Prerender() function not the Page_Load() function. The value of Message attribute will be initialized from the value in the HTML (aspx page), however, the value can be changed later on by simply using “myControl.Message = … ” if required and the state will be maintained.

public partial class SimpleUserControl : System.Web.UI.UserControl {
  public String Message {
    get { object o = ViewState["Message"]; return (o == null) ? (String.Empty) : ((String)o); }
    set { ViewState["Message"] = value; }
  }
  protected void Page_Prerender(object sender, EventArgs e) {
    lblMessage.Text = Message;
  }
}
<%@ Control Language="C#"
  AutoEventWireup="true"
  CodeFile="SimpleUserControl.ascx.cs"
  Inherits="SimpleUserControl" %>
<h1><asp:Label ID="lblMessage" runat="server" Text=""></asp:Label></h1>

To use the control on a simple webpage just add the following.

<%@ Register TagPrefix="my" TagName="SimpleUserControl"  Src="~/controls/SimpleUserControl.ascx" %>
<my:SimpleUserControl ID="myControl" Runat="Server" Message="Hello World!" />

If you want to use it in a DataList (for example) just do this…

<asp:DataList ID="projectDataList" runat="server" DataSourceID="projectDataSource">
  <ItemTemplate>
   <my:SimpleUserControl ID="myControl" Runat="Server" Message='<% Eval("Title") %>' />
  </ItemTemplate>
</asp:DataList>
Advertisements

Posted in C#.NET | Leave a Comment »