C# 将空白选择项添加到下拉列表中的列表中

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

Adding a blank selection item to the list in drop down list

c#asp.netdrop-down-menu

提问by sarsnake

my dropdownlist is populated from the database as in:

我的下拉列表是从数据库中填充的,如下所示:

DataTable dt = GetData(); ddlMylist.DataSource = dt; ddlMylist.DataBind();

数据表 dt = GetData(); ddlMylist.DataSource = dt; ddlMylist.DataBind();

Now dt contains the data, and I wish to add "Select" word to the top of the list when the selection is blank. It seems as there is no option other than add it to the dt (DataTable object)....but it seems wrong somehow.

现在DT包含数据,并且在选择空白时,我希望将“选择”单词添加到列表顶部。似乎除了将其添加到 dt(DataTable 对象)之外别无选择……但不知何故似乎是错误的。

What are other options. It's doesn't have to be the word "Select" it can be just an empty space...Currently, upon page load I can see the first data item in the list which is all good and dandy, but I have 3 drop downs that are co-dependent, and I want the user to explicitly make a selection which will trigger other drop downs to populate accordingly.

还有什么其他选择。它不一定是“选择”这个词,它可以只是一个空白空间......目前,在页面加载时,我可以看到列表中的第一个数据项,这一切都很好,但我有 3 个下拉列表是相互依赖的,我希望用户明确做出一个选择,这将触发其他下拉菜单相应地填充。

采纳答案by Phil Sandler

Try:

尝试:

ddlMylist.Items.Insert(0, new ListItem([key], [text]));
ddlMylist.SelectedIndex = 0;

You do this after you databind to your source.

在数据绑定到源之后执行此操作。

回答by Cory Charlton

Try:

尝试:

DDL.Text = string.Empty;

Edit:

编辑:

I know this works when I'm manually adding items but I'm not sure if it will when a DataSource is bound.

我知道这在我手动添加项目时有效,但我不确定在绑定 DataSource 时是否有效。

回答by Joel Coehoorn

Your dropdownlist markup should look like this:

您的下拉列表标记应如下所示:

<asp:DropDownList ID="ddlMylist" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Text="-Select-" Value="" />
</asp:DropDownList>

Note the AppendDataBoundItemsattribute.

注意AppendDataBoundItems属性。

回答by COMPILER

Try this one:

试试这个:

ddlMylist.Items.Insert(0, "Select");