Followers

Friday, 18 January 2013

How to create and use User Control in asp.net


Here I show how to create and use user control in asp.net. In this simple example first I create a user control name ColorUserControl.ascx which shows a color ListBox. When someone select a color then the Label control show its name. Next I place this user control in a web form name Default.aspx. Here is the source code of both files.


ColorUserControl.ascx

  1. <%@ Control Language="C#" ClassName="ColoruserControl" %>  
  2.   
  3. <script runat="server">  
  4.     protected void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e) {  
  5.         Label1.Text = "Your selected color: " +  
  6.             ListBox1.SelectedItem.Text.ToString();  
  7.     }  
  8. </script>  
  9.   
  10. <asp:Label ID="Label1" runat="server" Font-Size="Medium" ForeColor="DeepPink"></asp:Label>  
  11. <br /><br />  
  12. <asp:Label ID="Label2" runat="server" Text="Choose Color" AssociatedControlID="ListBox1"></asp:Label>  
  13. <asp:ListBox ID="ListBox1" runat="server" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" AutoPostBack="true">  
  14.     <asp:ListItem>DarkSalmon</asp:ListItem>  
  15.     <asp:ListItem>DarkOliveGreen</asp:ListItem>  
  16.     <asp:ListItem>DarkMagenta</asp:ListItem>  
  17.     <asp:ListItem>DarkOrchid</asp:ListItem>  
  18.     <asp:ListItem>DarkSeaGreen</asp:ListItem>  
  19.     <asp:ListItem>DarkTurquoise</asp:ListItem>  
  20.     <asp:ListItem>DarkViolet</asp:ListItem>  
  21.     <asp:ListItem>DeepPink</asp:ListItem>  
  22. </asp:ListBox>  

 

Default.aspx

  1. <%@ Page Language="C#" %>  
  2.   
  3. <%@ Register Src="ColorUserControl.ascx" TagName="ColorUserControl" TagPrefix="uc1" %>  
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  5.   
  6. <script runat="server">  
  7.   
  8. </script>  
  9.   
  10. <html xmlns="http://www.w3.org/1999/xhtml">  
  11. <head runat="server">  
  12.     <title>How to create and use User Control in asp.net</title>  
  13. </head>  
  14. <body>  
  15.     <form id="form1" runat="server">  
  16.     <div>  
  17.         <h1>Page Top</h1>  
  18.         <hr />  
  19.         <h2>User Control</h2>  
  20.         <uc1:ColorUserControl ID="ColorUserControl1" runat="server" />  
  21.         <hr />  
  22.         <h3>Page Footer</h3>  
  23.     </div>  
  24.     </form>  
  25. </body>  
  26. </html>  




No comments:

Post a Comment