INSERT A LISTITEM TO A DROPDOWNLIST

Lillian Martin

Total Post:27

Points:189
Posted by  Lillian Martin
C#
 781  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. Maria Susan

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!