April 11, 2013

User Controls

A user control is a kind of composite control that works much like an ASP.NET Web page—you can add existing Web server controls and markup to a user control, and define properties and methods for the control. You can then embed them in ASP.NET Web pages, where they act as a unit.

To include a user control in a Web Forms page

In the containing ASP.NET Web page, create an @ Register directive that includes:

TagPrefix attribute, which associates a prefix with the user control. This prefix will be included in opening tag of the user control element.

TagName attribute, which associates a name with the user control. This name will be included in the opening tag of the user control element.

Src attribute, which defines the virtual path to the user control file that you are including.

In User control page:-     File name = WebUserControl.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs"
    Inherits="WebUserControl" %>
<asp:TextBox ID="txtDateControl" runat="server"></asp:TextBox><asp:Calendar ID="dtpicker"

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="DemoWebUserControl.ascx.cs" Inherits="DemoWebUserControl" %>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />

In my web form we need to register user control.

<%@ Register TagPrefix="Uc1"  TagName="UserControl" Src="~/DemoWebUserControl.ascx"  %>

Added user control in my page

        <Uc1:UserControl   ID="ddl1" runat="server" />

        <asp:Button ID="btnSubmit" runat="server" Text="Submit"
            onclick="btnSubmit_Click" />

Now if we want to access the textbox and calendar control in my code behind file, we use following code.

    protected void btnSubmit_Click(object sender, EventArgs e)


        DropDownList  ddl1 = (DropDownList)dtpicker.FindControl("ddl1");
        txt.Text = ddl1.SelectedValue.ToString();

        spMsg.InnerText = txt.Text;


In above code to get control values of Calendar and Textbox we need to FindControl method.
Then we can easily access values of these controls.

No comments:

Post a Comment