Contents
Binding to Function
Using a DropDownList to select a state from a list of states is a common need. This page will detail building the list, setting the initial value and geting the return value. First the function containing the state abbreviations. Pass an integer value from 0 to 50 (including DC for District of Columbia there are 51 entries) and a string containing the associated abbreviation. The all states function is in our library and is alphbetical by state abbreviation. We also have a second set that is alphabetical by state name. The second set shows the state name in the DropDownList text area and holds the state abbreviation in the value area.
public static string AllStates(int wh)
{
string [] bStates =
{ "AK","AL","AR","AZ","CA", // 1
"CO","CT","DC","DE","FL", // 2
"GA","HI","IA","ID","IL", // 3
"IN","KS","KY","LA","MA", // 4
"ME","MD","MI","MN","MO", // 5
"MS","MT","NC","ND","NE", // 6
"NH","NJ","NM","NV","NY", // 7
"OH","OK","OR","PA","RI", // 8
"SC","SD","TN","TX","UT", // 9
"VA","VT","WA","WI","WV", //10
"WY"}; //11
if (wh>=0 && wh<51) return bStates[wh];
return null;
}
In the code behind page, we call the function to add the state abbreviations to the DropDownList. Notice the last line - we use the FindByText method to initialize the control with the proper state. If Adr.State contained "IL", the initial value of the DropDownList would be IL.
ddState.Items.Clear();
for (short i=0; i<51; i++)
ddlState.Items.Add(new ListItem(AllStates(i) ));
ddlState.Items.FindByText(Adr.State).Selected=true;
Extracting the proper value is simple. We merely assign the Adr.State variable with the value contained in Selected.Item.Text.
Adr.State = ddlState.SelectedItem.Text;
Top 