Home > DeveloperSection > Forums > Insert a ListItem to a DropDownList
Lillian Martin

Total Post:27

Points:189
Posted on    May-27-2015 7:59 AM

 C# Dropdown  list 
Ratings:


 1 Reply(s)
 459  View(s)
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"));

        }

}



Maria Susan

Total Post:29

Points:107
Posted on    May-27-2015 8:08 AM

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


Don't want to miss updates? Please click the below button!

Follow MindStick