DropDownList,获取 C# 中返回的 DataValueField

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17348678/
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-10 09:15:11  来源:igfitidea点击:

DropDownList, getting DataValueField returned in C#

c#asp.net.netvisual-studio

提问by David Tunnell

I have a drop down list that pulls data from a database to show some of its options:

我有一个下拉列表,可以从数据库中提取数据以显示其中的一些选项:

    <asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="SqlDataSource1"
        DataTextField="Name" DataValueField="PK_Task" AppendDataBoundItems="true" CssClass="dropDownList">
        <asp:ListItem Selected="True">General Support</asp:ListItem>
        <asp:ListItem>Vacation</asp:ListItem>
        <asp:ListItem>Sick Leave</asp:ListItem>
        <asp:ListItem>Something Else</asp:ListItem>
    </asp:DropDownList>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
        SelectCommand="SELECT [PK_Task], [Name] FROM [Task] WHERE ([PointPerson] LIKE '%' + @PointPerson + '%') AND [Status] NOT LIKE 'Done'">
        <SelectParameters>
            <asp:QueryStringParameter Name="PointPerson" Type="String" />
        </SelectParameters>
    </asp:SqlDataSource>

As you can see, I only display the [Name] column:

如您所见,我只显示 [Name] 列:

DataTextField="Name" 

But I am also getting the primary key SELECT [PK_Task], [Name] FROM:

但我也得到了主键 SELECT [PK_Task], [Name] FROM:

DataValueField="PK_Task"

How do I get access to this primary key based on user selection. If a user selects a specific 'name' from the drop down menu, what C# can I use to get the corresponding primary key returned to me so I can save it in a variable?

如何根据用户选择访问此主键。如果用户从下拉菜单中选择特定的“名称”,我可以使用什么 C# 来获取返回给我的相应主键,以便将其保存在变量中?

The closest I have gotten is this, but all it does is return the string "PK_Task":

我得到的最接近的是这个,但它所做的只是返回字符串“PK_Task”:

String taskID = DropDownList3.DataValueField;

采纳答案by Felipe Oriani

You can use the SelectedValueproperty:

您可以使用该SelectedValue属性:

// to set
DropDownList3.SelectedValue = "1";

// to read
string value = DropDownList3.SelectedValue;

回答by COLD TOLD

try this

尝试这个

String taskID = DropDownList3.SelectedItem.Value;

回答by Md. Parvez Alam

any way you can use either

任何你可以使用的方式

dropdown3.selectedvalue

or

或者

dropdown3.selecteditem.value