将ListItem插入DropDownList

时间:2015-01-23 15:26:05

标签: c# asp.net

我正在尝试在下拉列表的开头添加一个ListItem。我不知道为什么这段代码不起作用。它只添加数据库信息。我创建了一个继承自DropDownList的类,以便自定义我自己的下拉列表。

public class MyDropDownList : DropDownList
{
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.BindItems();
        }

        private void BindItems()
        {
            this.Items.Clear();
            this.DataSource = this.GetData();
            this.DataValueField = "CompositePK";
            this.DataTextField = "Description";
            this.DataBind();
            this.Items.Insert(0, new ListItem("-Select-", "-1"));
        }
}

2 个答案:

答案 0 :(得分:0)

您必须插入一个新的ListItem:

this.Items.Insert(0, new ListItem("", "-Select-"));

答案 1 :(得分:0)

当列表仍为空时,您的代码会在调用DataBind()之前调用Insert()DataBind()读取控件的源并生成相应的元素,而不监视将来的任何更改。

您需要撤消通话顺序:

this.Items.Insert(0, new ListItem("-1", "-Select-"));
this.DataBind();
相关问题