user505210
user505210

Reputation: 1402

selected index value of dropdownlist

I have a very simple dropdownlist in a webpart as below.When I run this webpart the Dropdownlist always has One selected but I was thinking -1 makes it not select any value.Am I doing something wrong here.

DropDownList list = new DropDownList();
list.Items.Add("One");
list.Items.Add("Two");
list.Items.Add("Three");
list.SelectedIndex = -1;
this.Controls.Add(list);

Upvotes: 2

Views: 1668

Answers (2)

Nudier Mena
Nudier Mena

Reputation: 3274

Try with this, but it seems to be strange behavior with the ddl control, the drop down list always selected the item in 0 position.

        DropDownList list = new DropDownList();
        list.Items.Add("");
        list.Items.Add("One");
        list.Items.Add("Two");
        list.Items.Add("Three");
        this.form1.Controls.Add(list);
        list.SelectedIndex = 0;

Upvotes: 0

SMS
SMS

Reputation: 462

Add an item like "-- SELECT --" and make it selected as default

DropDownList list = new DropDownList();
list.Items.Add("-- SELECT --");
list.Items.Add("One");
list.Items.Add("Two");
list.Items.Add("Three");
list.SelectedIndex = 0;
this.Controls.Add(list);

Also look into DropDownList.ClearSelection() method.

Hope it helps.

Upvotes: 2

Related Questions