Insert a ListItem to a DropDownList

Total Post:27

Points:189
C#
 1105  View(s)
Ratings:
Rate this:

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

  1. Post:29

    Points:107
    Re: Insert a ListItem to a DropDownList

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

      Modified On Apr-09-2018 11:33:57 PM

Answer