简体   繁体   English

如何在下拉列表中插入项目作为最后一个选项

[英]How to insert item as LAST option in a dropdown list

I know to add an item as the first item, I use: 我知道要添加一个项目作为第一项,我使用:

ddlTest.Items.Insert(0, new ListItem("---New First Item---", "-1"));

I tried -1 as the index but then I didn't even see the item. 我尝试-1作为索引,但后来我甚至没有看到该项目。 How to I add an item as the last item in the list without knowing its index number (because the dropdown is populated from a database)? 如何在不知道索引号的情况下添加项目作为列表中的最后一项(因为下拉列表是从数据库中填充的)?

to add to the LAST position, just add to the list as 要添加到最后位置,只需添加到列表中即可

ddlTest.Items.Add(new ListItem("---New First Item---", "-1"));

as it will append to the last place by default. 因为它会默认附加到最后一个位置。

您可以使用列表的大小或长度作为索引,因为长度等于最后一个位置加一。

You can easily do that by adding first all the items and after that, add one based on the index. 您可以通过首先添加所有项目来轻松完成此操作,然后根据索引添加一个项目。 You know that once your items are in the list. 您知道,一旦您的物品在列表中。

Here's some code: 这是一些代码:

// Fill dropdownlist with data from database.
int index = ddlTest.Items.Count;

// You don't need to add or subtract one, because count is starting from 1, while the index starts from 0. 

ddlTest.Items.Insert(index, 0, new ListItem("--- New First Item---", "-1");

I believe that this should work. 我相信这应该有效。

Remove the 0 from your Add method. Add方法中删除0 It will automatically detect that the item has to be added at the end. 它会自动检测到最后必须添加项目。

ddlTest.Items.Add(new ListItem("---New First Item---", "-1"));

Try this one 试试这个吧

dropDownList.Items.Add(new ListItem("AddNew","AddNew")); dropDownList.Items.Add(new ListItem(“AddNew”,“AddNew”));

ref: http://www.aspsnippets.com/Articles/Programmatically-add-items-to-DropDownList-on-Button-Click-in-ASPNet-using-C-and-VBNet.aspx 参考: http//www.aspsnippets.com/Articles/Programmatically-add-items-to-DropDownList-on-Button-Click-in-ASPNet-using-C-and-VBNet.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM