I have the following asp:dropdownlist: (see code snippet).
I am holding user addresses in my database. The "State" column in the database is/will be updated using the same dropdownlist, so when a user selects 'AZ' from the dropdownlist a "2" will be sent to the database to be stored in the "State" column.
My problem is programmatically changing the selected item of the dropdownlist, based on what I pull from the database. If I use ddlState.SelectedIndex = 4 (or whatever number within my range) it works just fine. However I need to pull the # from the database. I have tried all manner of things, and getting several different errors. Here are a few things I've tried that aren't working.
1. ddlState.SelectedIndex = myDataReader["State"];
Error: CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?)
2. ddlState.SelectedIndex = Convert.ToInt32(myDataRead
tion: Cannot have multiple items selected in a DropDownList.
3. ddlState.SelectedIndex = ddlState.Items.IndexOf(ddl
No Error, but does nothing......Index 0 ends of being selected.
4. int i = myDataReader["State"];
Error: System.Web.HttpException: Cannot have multiple items selected in a DropDownList.
Errors in 2 and 4 are happening I because Index 0 is Selected on Page Load, but I don't understand how this error is happening if the SelectedIndex is being changed before the page is refreshed on a postback?
Please offer advice. I'm open to change the way I am doing this as well, if a better methodology exists.
<asp:DropDownList ID="ddlState" runat="server">
<asp:ListItem Value="0" Text="AL" />
<asp:ListItem Value="1" Text="AK" />
<asp:ListItem Value="2" Text="AZ" />
<asp:ListItem Value="3" Text="AR" />
<asp:ListItem Value="4" Text="CA" />
<asp:ListItem Value="5" Text="CO" />
//Rest of the 45 States