Retrieve the Selected Item of a DropDownList kept inside a UserControl

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

DropDownList Inside UserControl



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: