简体   繁体   中英

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

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();
    }
}

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

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

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

尝试以下代码;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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