Dynamically Selecting a Value in a C# DropdownList Control

By XeroCube | October 10, 2013

In a recent internal C# web project, I needed to accept a URL parameter and use that value to select an item value, if it exists, within a DropDownList control. I have provided the code, along with some commentary, to use as a refresher for myself and a base for others.

This code was implemented within my page’s Page_Load event outside of an IsPostBack check.

//Check for URL Parameters
if (Request.QueryString.Count > 0)
      if (!string.IsNullOrEmpty(Request.QueryString[“Value”]))
           // If TestPlan parameter is not null, attempt to find the value in the release filter dropdown
           if (DropDownListbox.Items.FindByText(Uri.UnescapeDataString(Request.QueryString[“Value”].ToString())) != null)
                // Found the item in the release filter dropdown. Select it and load the filtered data.
                DropDownListbox.Items.FindByText(Uri.UnescapeDataString(Request.QueryString[“Value”].ToString())).Selected = true;
                // Continue processing
                 // Could not find the value in the release filter dropdown.
                 //do something else


Topics: Code, Tech | No Comments »