How to add an item to a drop down list in asp.net

荒凉一梦 提交于 2019-12-03 06:36:44

问题


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

I want to add the "Add new" at a specific index


but I am not sure of the


syntax


回答1:


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

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



回答2:


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



回答3:


Try following code;

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


来源:https://stackoverflow.com/questions/17468956/how-to-add-an-item-to-a-drop-down-list-in-asp-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!