Etienne
Etienne

Reputation: 7201

Cant get text of a DropDownList in code - can get value but not text

I am using ASP.NET 3.5

I have a drop-down list called lstCountry with an item in it like this:

<asp:ListItem Value="United States">Canada</asp:ListItem> 

This will display Canada but in code the value will be "United States". How can I retrieve the value "Canada" also in my code?

I have tried all of these and all of them return "United States"

lstCountry.Text
lstCountry.SelectedValue
lstCountry.SelectedItem.Text

My Drop Down list:

 <asp:DropDownList ID="lstCountry" runat="server" Width="200px">
              <asp:ListItem>Please Select</asp:ListItem>
  <asp:ListItem>United States</asp:ListItem>
  <asp:ListItem Value="United States">Canada</asp:ListItem>
 </asp:DropDownList>

How I read the value in code:

    Dim country As String
    country = lstCountry.SelectedItem.Text

Upvotes: 19

Views: 111559

Answers (7)

Dameon
Dameon

Reputation: 1

had the same problem and just solved it, i used string [variable_Name] =dropdownlist1.SelectedItem.Text;

Upvotes: 0

john
john

Reputation: 33

AppendDataBoundItems="true" needs to be set.

Upvotes: 3

Tom
Tom

Reputation: 69

Have a look here, this has a proof-of-concept page and demo you can use to get anything from the drop-down: asp:DropDownList Control Tutorial Page

Upvotes: -1

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

add list using

<asp:ListItem Value="United States" Text="Canada"></asp:ListItem>

and then try

DropDownList1.SelectedItem.Text

I found your mistake.

<asp:ListItem>United States</asp:ListItem> 

change this to

<asp:ListItem>United States1</asp:ListItem> 

Then you will got the actual value.

What was the issue is, there are two same values in your dropdown, when page postback, it take first value as selected and give the result accordingly. if you noticed when after postback United State Value is selected

Upvotes: 42

rahul
rahul

Reputation: 187070

What about

lstCountry.Items[lstCountry.SelectedIndex].Text;

Upvotes: 1

Himadri
Himadri

Reputation: 8876

You can try

lstCountry.SelectedItem.Text

Upvotes: 0

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50752

try

lstCountry.SelectedItem.Text

Upvotes: 0

Related Questions