C# 无法在代码中获取 DropDownList 的文本 - 可以获取值但不能获取文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1593399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:08:01  来源:igfitidea点击:

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

c#.netasp.netvb.netdrop-down-menu

提问by Etienne

I am using ASP.NET 3.5

我正在使用 ASP.NET 3.5

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

我有一个名为 lstCountry 的下拉列表,其中有一个项目,如下所示:

<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

采纳答案by Muhammad Akhtar

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

问题是,下拉列表中有两个相同的值,当页面回发时,它会选择第一个值并相应地给出结果。如果您注意到选择回发后美国值的时间

回答by Arsen Mkrtchyan

try

尝试

lstCountry.SelectedItem.Text

回答by Himadri

You can try

你可以试试

lstCountry.SelectedItem.Text

回答by rahul

What about

关于什么

lstCountry.Items[lstCountry.SelectedIndex].Text;

回答by Tom

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

看看这里,它有一个概念验证页面和演示,您可以使用它从下拉列表中获取任何内容: asp:DropDownList Control Tutorial Page

回答by john

AppendDataBoundItems="true"needs to be set.

AppendDataBoundItems="true"需要设置。

回答by Dameon

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

遇到了同样的问题并刚刚解决了它,我使用了字符串 [variable_Name] =dropdownlist1.SelectedItem.Text;