C# 如何将项目添加到 ASP.NET 中的下拉列表?

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

How to add an item to a drop down list in ASP.NET?

c#asp.netdrop-down-menu

提问by Scorps

I want to add the "Add new" at a specific index, but I am not sure of the syntax. I have the following code

我想在特定索引处添加“添加新”,但我不确定语法。我有以下代码

protected void Page_Load(object sender, EventArgs e)
{
        DRPFill();
        if (!IsPostBack)
        {
            DropDownList1.Items.Add("Add New");
        }
}

    public void DRPFill()
    {
        if (!IsPostBack)
        {
            //Object
            AddMajor objMajor = new AddMajor();

            //Data Table
            DataTable dtMajor = objMajor.find();

            //Data Source
            DropDownList1.DataSource = dtMajor;
            DropDownList1.DataValueField = "MajorID";
            DropDownList1.DataTextField = "MajorName";

            //Data Bind
            DropDownList1.DataBind();
        }
    }

回答by Ben Gulapa

Try this, it will insert the list item at index 0;

试试这个,它会在索引 0 处插入列表项;

DropDownList1.Items.Insert(0, new ListItem("Add New", ""));

回答by Full Time Skeleton

Which specific index? If you want 'Add New' to be first on the dropdownlist you can add it though the code like this:

具体哪个指标?如果您希望“添加新”成为下拉列表中的第一个,您可以通过如下代码添加它:

<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server">
     <asp:ListItem Text="Add New" Value="0" />
</asp:DropDownList>

If you want to add it at a different index, maybe the last then try:

如果您想将它添加到不同的索引,也许是最后一个,然后尝试:

ListItem lst = new ListItem ( "Add New" , "0" );

DropDownList1.Items.Insert( DropDownList1.Items.Count-1 ,lst);

回答by Full Time Skeleton

Try following code;

尝试以下代码;

DropDownList1.Items.Add(new ListItem(txt_box1.Text));