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">

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;

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;


DropDownList Inside UserControl

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: