State & Country validation. Problems getting back correct state.SelectedItem.Text

I am trying to validate a web form that accepts a users address. Among other fields there is one DropDownList  for State/Province:

<asp:Label ID="lblstate" AssociatedControlID="state" runat="server" Text="State/Province" />
<asp:RequiredFieldValidator ID="state_required" runat="server" ControlToValidate="state" ErrorMessage="State/Province is required." Text="*" />
<asp:DropDownList ID="state" runat="server" />

And one DropDownList for Country:

<asp:Label ID="lblcountry" AssociatedControlID="country" runat="server" Text="Country" />
<asp:RequiredFieldValidator ID="country_required" runat="server" ControlToValidate="country" ErrorMessage="Country is required." Text="*" />
<asp:CompareValidator ID="StateCountryMatch" runat="server" ControlToValidate="state" ControlToCompare="country" ErrorMessage="The state and country you entered don't match up." Text="*" />
<asp:DropDownList ID="country" runat="server" />

In the code behind I popuplate each DropDownList from an XML file (states.xml and countries.xml)

//Populate States List
DataSet states = new DataSet();
state.DataSource = states;
state.DataTextField = "name";
state.DataValueField = "countryid";
//Prepend States List with "Select One"
state.Items.Insert(0, new ListItem("Select One", ""));

//Populate Countries List
DataSet countries = new DataSet();
country.DataSource = countries;
country.DataTextField = "name";
country.DataValueField = "id";
You can see that the VALUE attribute of the state drop down list becomes the countryID of that state. So for example, the resulting HTML in the browser looks like this:

<select name="state" id="state">
<option value="">Select One</option>
<option value="1">Alabama</option>
<option value="1">Alaska</option>
<option value="1">Arizona</option>
... etc ...
<option value="2">Alberta</option>
<option value="2">British Columbia</option>
<option value="2">Manitoba</option>

And then the Country drop down looks like this:
<select name="country" id="country">
<option selected="selected" value="1">United States</option>
<option value="2">Canada</option>

So when the validation runs it compares that the value of State matches the Value of Country. And this method seems to works great.

Now, the problem is that when I try to access the name of the chosen state, it always comes back as Alabama (the first state in the list). I am using the following code:

Why won't it return the selected items Text value? If I select Calfornia from the list I would expect to have access the the string "California" through the SelectedItem.Text property.

If this method of validation won't work... for whatever reason. What other options do I have??

Thanks for the help!

Please let me know if I left out any details
8/21/2006 8:51:38 PM 93655 articles. 5 followers. Follow

5 Replies

Similar Articles

[PageSpeed] 14

Are you binding the dropdown lists on every request, including postbacks?  If you are on a postback, you're probably resetting everything when the page reloads itself.  Do something like:

if (!this.IsPostBack)
   // Bind drop down lists

8/22/2006 1:49:09 AM
Thanks, I added that but I'm still getting the same results. I posted an demo along with the full source code here: so you can see exactly what's going on.
8/22/2006 6:54:59 PM
That's weird, because the list is resetting itself on post back.  Did you step through the debugger to see what happens on post back?

8/22/2006 7:07:03 PM
Well upon PostBack it does skip over the DataBind() method. So I'm really at a loss here.

It seems as if for some reason it doesn't like the fact that all of the VALUE attributes in the states dropdown menu have the same value (1 for US states, and 2 for Canadian Provinces).

If I choose a Canadian Province, and Canada as the country, it will output the first Canadian Province in the list (Alberta), just like it outputs the first US State (Alabama) when choosing from US states. It seems as if it can't distinguish between non-unique values even though the name is unique, and the index obviously has to be unique.
8/22/2006 9:11:06 PM

When the control is rebuilt after a postback, .NET will use the post data to reset the values of the various controls to what the user had selected.  in the case of a DDL, .NET will grab the ddl's selected value that was posted and then uses that value to find the listitem with a matching value.  This listitem is then marked as selected.

If you look at how the ddl implements FindByValue, you will see a For/Each loop that iterates over the listitems checking the values as it goes.  It will stop at the first listitem with a matching value.

Bottom line is that putting multiple items into a DDL that all share the same value is not recommended.

Mike Banavige

Need a site code sample in a different language? Try converting it with:
8/22/2006 9:40:38 PM

Similar Artilces:

superreview requested: [Bug 285285] Add SINGLE_LINE state to single line text inputbox : [Attachment 176741] Clean up form control and text field state code, add single line extended state support
Louie Zhao <> has asked Henry Jia <> for superreview: Bug 285285: Add SINGLE_LINE state to single line text inputbox Attachment 176741: Clean up form control and text field state code, add single line extended state support ...

superreview granted: [Bug 285285] Add SINGLE_LINE state to single line text inputbox : [Attachment 176741] Clean up form control and text field state code, add single line extended state support
Henry Jia <> has granted Louie Zhao <>'s request for superreview: Bug 285285: Add SINGLE_LINE state to single line text inputbox Attachment 176741: Clean up form control and text field state code, add single line extended state support ...

Problem with the web form state (when refreshing)
let say ..if i click a button , it perform following action called "A" then i refresh the page automatically run the button click again, thus calling action "A" how do i prevent this ? is there anything to do with the view state? Hi, Button action usually performed in Button_Click postback event. Button is by default autopostback control. It means that Click event initiate postback imidiately. Code in Button_Click is not executed on other roundtrips (like other postback events or page refresh). It has nothing to do with ViewState.Leon LangleybenMCSD, ASP....

Problems losing the state with SQL Session State in a Web Farm
Having a huge problem using different IIS servers and one SQL Server State. When the user goes from computer A to B the B computer quicks him out to Login again. Any solution? Cheers Al  CheersAlMy BlogMapStats.NETPlease click on 'Mark as Answer' if this post answered your question! Searched the KB: Hope it will help....

Issues with getting selecteditem.text from a web form
I am attempting to make a list box where users can be added to the database. I have created two list boxes and I have managed to transfer the values across. However I am having difficulty in getting the selected index value of the item, which has been selected. I need the selected item to add the user ID of the selected user into the database. Any help would be great. The first part binds the data to the lstproducts listbox the second parts writes data to the database Sub list() Dim Conn As OracleConnection Dim cmdselect As OracleCommand Dim ...

Need to keep form state and load form state from file
I have a form with regular html selectboxes (controlled by javascript to push items around the selectboxes). I need to find a way to keep the state of these items even after an button click event (which loads some session variables with the values of the form and makes a page.registerstartupscript for opening search results in a new window). I was thinking that the same principles used when keeping the state might also be useful for loading the state from a specially formatted file. At the moment I try the following: - on submit of form the hiddenfields are loade...

VB .net Web Form will not get contents of Text Box
I have created a web form with text boxes that are bound to a DataSet/DataView.  I have created button to navigate up and down the recordset.  That all works fine. I need to have the ability to edit/add text in any of the boxes and then when clicking "Save" button, it would build an UPDATE query to send to the database. When the Save button is clicked, I have coded to DIM a string var (strSQL) to use to build the SQL command.  For some reason, it will only get the text from a text box if the data was pulled the database.  If I add/edit data, then the SQL command will ha...

superreview requested: [Bug 388387] [FIX] Avoid generating state keys for form restoration if there's no state to get
Boris Zbarsky <> has asked Jonas Sicking <> for superreview: Bug 388387: [FIX]Avoid generating state keys for form restoration if there's no state to get Attachment 272591: Like so ------- Additional Comments from Boris Zbarsky <> This is a bit of a hack.... Right now, during initial load of a page, we generate form state keys for form controls, even though there is no state to get. I'm...

superreview granted: [Bug 388387] [FIX] Avoid generating state keys for form restoration if there's no state to get
Jonas Sicking <> has granted Boris Zbarsky <>'s request for superreview: Bug 388387: [FIX]Avoid generating state keys for form restoration if there's no state to get Attachment 272591: Like so ...

Validating States dropdownlist with all other validation controls on form?
I have States dropdownlist  starts with "--" ListItem and 50 States. If user select "--" first ListItem, I need validate at client. Right now I am doing code behind side validation. But I have other controls on the form for validation, So I need to validate all at time. on submit button click.   Hi Srikanth, Place a required field for states dropdown list and set the "intial value" property of required field validator to "--". On Submit click validation is done. Above is the solution if i am not misunderstood you.   Regards, Pra...

Sharing state between Web form and Web service
Folks, My Web application exposes some Web services. It also is a consumer of its own services. Here is my Web service class:    public class Service1 : System.Web.Services.WebService {        public const string VAL = "val";        [WebMethod(EnableSession = true)]        public string Getvalue() {            object val = Session[VAL];            return...

Getting undefined value while using view state in Web Form Designer generated code
hi,    i am trying to get the drop down list selected value in Web Form Designer generated code,when i am trying it with view state i am getting some undefined value.please help me regarding this.. i am trying with the following code.        refinery =  ddRefineries.SelectedRefinery; ViewState.Add("ref1",refinery); #region Web Form Designer generated code        override protected void OnInit(EventArgs e)        {          &nbs...

when adding web reference, I get "Operation is not valid due to the current state of the object."
 Hello.I am trying to add a Web reference to a project.  So, I do the standard: right clicking on the project and select "Add Web Reference". The Add Web Reference appears and I navigate to the desired URL "" and click "Go".   This works in IE.  I see the results and two methods in the window.  However,  the "Add Reference" button and " Web Reference Name" texbox is disabled. And, I see the Operation is not valid due to the current state of the object." I ...

.Net Web Form & Web Service Deployment
Hi all I have written some test web services and some web form applications and deployed them to my IIS. That's fine but I now want to deploy them to my real IIS server. I have created an msi for each but the problem is I seem to only be able to deploy to the default web site. Our default web site is turned off and instead we use several other sites. Does anybody happen to if Powerbuilder 11 supports non default web sites? If not do I need to hack the msi and if so can anybody suggest a suitable tool. I have Orca but it's not very friendly. Unless of course I knew exactly w...

Web resources about - State & Country validation. Problems getting back correct state.SelectedItem.Text -

GridView SelectedItem Binding Gotcha in WinRT
... this template will create a bunch to boiler plate code for you and I was taking this code and extending it. When I was setting up my SelectedItem ...

User Anna Lear - Stack Overflow
current community chat blog Stack Overflow Meta Stack Overflow Stack Overflow Careers your communities Sign up or log in to customize your list. ...

Index - 2,000 Things You Should Know About WPF
Below is a list of all posts created so far for the 2,000 Things You Should Know About WPF blog. Total number of posts = 1,077 Animation #7 - ...

Authorities eye retirement accounts as possible tax dodges - World News
{atrb}”,”template_name”:”sm_thmb_play_ttle_atrb”,”i18n”:{“end_of_gallery_header”:”End of Gallery”,”end_of_gallery_next”:”View Again”},”metad ...

A Giftly is not a gift card, it's better. Give a Giftly for any item or experience, at any business. Giftly is the fastest and easiest way to ...
A user on the expression forums asked a question about how they could activate a specific tab item on a screen being navigated to. Below is a ...

Cheap Event Tickets – bringing u the cheapest event ticket deals daily!
‘},”otherParams”:{“t_e”:1,”.intl”:”US”},”events”:{“fetch”:{lv:2,”sp”:”2146252129″,”ps”:”LREC,N,NT1,RICH”,”npv”:true,”bg”:”#FFFFFF”,”em”:esca ...

Silverlight Toolkit - Download: Silverlight for Windows Phone Toolkit - Feb 2011
... various null check improvements. Refactoring of much of the code, improvements to item recycling, conforming with ListBox with respect to SelectedItem ...


Welcome to Surface
Welcome to Surface 2.0

Resources last updated: 1/16/2016 9:42:10 PM