I have often seen developers struggling with accessing properties of controls kept inside a UserControl. This post will show you how to retrieve the selected Item of a DropDownList kept inside a UserControl.
Let us assume that we have a UserControl called UserControlOne.ascx
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="UserControlOne.ascx.cs" Inherits="UserControlOne" %>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
The code to populate the UserControl is as shown below (UserControlOne.ascx.cs):
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string[] names = DateTimeFormatInfo.CurrentInfo.MonthNames;
DropDownList1.DataSource = names;
DropDownList1.DataBind();
}
}
We will now register this UserControl to a page as shown below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default16.aspx.cs"
Inherits="Default16" %>
<%@ Register TagPrefix="UC" TagName="DDL" src="UserControlOne.ascx"%>
Now to access the selected item of the dropdownlist kept inside the usercontrol, use the following code on the Button click event:
protected void btnFetch_Click(object sender, EventArgs e)
{
UserControl ucOne = ((UserControl)(FindControl("DDLOne")));
DropDownList ddlOne = ((DropDownList)(ucOne.FindControl("DropDownList1")));
if (ddlOne.SelectedIndex > -1)
Label1.Text = ddlOne.SelectedItem.Value;
}
OUTPUT
Tweet
No comments:
Post a Comment