KnowDotNet

Finding State FullName in DropDownList with Abbreviation

Using FindByValue in ASP.NET DropDownList

by Les Smith

I have a DropDownList of States, which has both the full name and abbreviated name.  How can I set the full name in the text portion of the DropDownList?

In a DropDownList on a couple of pages, I have a list of states.  The DataTable that is bound to the DropDownList is populated by a Stored Procedure that has the following Select code in it.

  SELECT     Name, ID, Abbreviation
  
FROM         States
  
ORDER BY Name

Name is the full name of each state.  Abbreviation is the two digit State Code.  Since the Text property of a DropDownList can not be set in code in an ASP.NET control as it can be in a WinForms ComboBox, you have to use a different approach.  In the Page_Load event, I call a method to Load the DropDownList.  It has the following code in it, where the GetStates() method will return a DataTable.

      ddlStates.DataSource = GetStates();
      ddlStates.DataBind();

In this particular page, I then load the various Text Boxes and controls from a Business Object that I have retrieved from a Data Helper in the Data Access Layer (DAL).  One of the fields coming from the database is the State field and it is the two digit abbreviation.  To set the associated index in the DropDownList to show the full name of the state, I use the following code.

      ddlStates.SelectedIndex =
           ddlStates.Items.IndexOf(ddlStates.Items.
           FindByValue(primaryAddress.State.Trim()));

When I get ready to save the selected state back to the database, I can access the abbreviated version of the state from the DropDownList using the following line of code.  Even though the Text of the DDL is "Georgia", the following line of code will pick up the abbreviated state code "GA".

      primaryAddr.State = ddlStates.SelectedValue;


Need to automatically organize your code windows?  You'll be amazed how easy it is to keep the code in your code windows organized.  TRY IT FREE FOR 30 DAYS BY CLICKING HERE.



Automatically generate braces in C#! Try CSharpCompleter and stop wasting valuable time needlessly typing hundreds of braces {} daily.  Try CSharpCompleter for 30 DAYS FREE.



Ask a Question, or give your feedback on my articles or products by going to the KnowDotNet Forum or by clicking on My Blog.
  

You can also email me directly at les@KnowDotNet.com.