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
- <%@ Control Language="C#" ClassName="ColoruserControl" %>
- <script runat="server">
- protected void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e) {
- Label1.Text = "Your selected color: " +
- ListBox1.SelectedItem.Text.ToString();
- }
- </script>
- <asp:Label ID="Label1" runat="server" Font-Size="Medium" ForeColor="DeepPink"></asp:Label>
- <br /><br />
- <asp:Label ID="Label2" runat="server" Text="Choose Color" AssociatedControlID="ListBox1"></asp:Label>
- <asp:ListBox ID="ListBox1" runat="server" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" AutoPostBack="true">
- <asp:ListItem>DarkSalmon</asp:ListItem>
- <asp:ListItem>DarkOliveGreen</asp:ListItem>
- <asp:ListItem>DarkMagenta</asp:ListItem>
- <asp:ListItem>DarkOrchid</asp:ListItem>
- <asp:ListItem>DarkSeaGreen</asp:ListItem>
- <asp:ListItem>DarkTurquoise</asp:ListItem>
- <asp:ListItem>DarkViolet</asp:ListItem>
- <asp:ListItem>DeepPink</asp:ListItem>
- </asp:ListBox>
Default.aspx
- <%@ Page Language="C#" %>
- <%@ Register Src="ColorUserControl.ascx" TagName="ColorUserControl" TagPrefix="uc1" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <script runat="server">
- </script>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>How to create and use User Control in asp.net</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <h1>Page Top</h1>
- <hr />
- <h2>User Control</h2>
- <uc1:ColorUserControl ID="ColorUserControl1" runat="server" />
- <hr />
- <h3>Page Footer</h3>
- </div>
- </form>
- </body>
- </html>
No comments:
Post a Comment