Insert a ListItem to a DropDownList

I'm trying to add an ListItem at the beginning of my dropdownlist. I don't know why this code is not working. It only adds the database information. I created a class that inherits from DropDownList in order to customize my own 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"));
        }
}

Last updated:5/27/2015 8:08:20 AM

1 Answers

Anonymous User
Anonymous User

Your code calls DataBind() before the call to Insert(), when the list is still empty. DataBind() reads the control's source and generates the appropriate elements without monitoring any future changes. 

You need to reverse the order of the calls: 

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

this.DataBind();

Answer