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

本文关键字:最后一个 选项 插入项目 下拉列表 | 更新日期: 2023-09-27 18:06:51

我知道添加一个项目作为第一项,我使用:

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

我尝试了-1作为索引,但我甚至没有看到项目。我如何添加一个项目作为最后项目在列表中不知道它的索引号(因为下拉框是从数据库填充)?

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

要添加到LAST位置,只需添加到列表

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

,因为它默认会附加到最后一个位置

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

您可以很容易地做到这一点,首先添加所有项目,然后根据索引添加一个。你知道,一旦你的项目在列表中。

下面是一些代码:

// 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");

Add方法中删除0。它将自动检测必须在末尾添加的项目。

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

试试这个

dropDownList.Items。添加新列("AddNew"、"AddNew")),

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