iJK
iJK

Reputation: 4765

Binding a dropdownlist and then adding a new listitem

I have a DropDownList which I initialize in a function called CreateChildControls before adding it to the Controls collections. I then override the Render() method and then render the DropDownList. The web part inherits from System.Web.UI.WebControls.WebParts.WebPart.

I bind the DropDownList in my web part like this:

private void BindClientTypes()
{
    DataTable dt = DB.GetAllClientTypes();

    if (dt == null)
    {
        ltGlobalErrorMsg.Text = GlobalErrorMessage;
        ltGlobalErrorMsg.Visible = true;
    }
    else
    {
        ddlClient.DataSource = dt;
        ddlClient.DataValueField = "ID";
        ddlClient.DataTextField = "Name";
        ddlClient.DataBind();
        ddlClient.Items.Insert(0, PleaseSelectItem);
    }
}

If I try to set the SelectedIndex of the DropDownList after calling DataBind, I get an error which says the control cannot have multiple selected items.

That code works fine, and I can set the SelectedIndex after the data bind if I comment out this line:

ddlClient.Items.Insert(0, PleaseSelectItem);

Can anyone explain why this wouldn't work?

Thanks.

Upvotes: 1

Views: 13624

Answers (2)

Kelsey
Kelsey

Reputation: 47726

ddl.Items.Add(new ListItem("yourtext", "yourvalue"));

When you set the 'selected' property you are setting it to that ListItem's instance so if you have more ListItems that you are reusing then they will all get the same value which is probably causing the issue you are experiencing.

To illustrate the problem see this example with 2 dropdownlists:

ListItem item1 = new ListItem("1", "1");
ListItem item2 = new ListItem("2", "2");
ListItem item3 = new ListItem("3", "3");

ddlTest.Items.Add(item1);
ddlTest.Items.Add(item2);
ddlTest.Items.Add(item3);

ddlTest2.Items.Add(item1);
ddlTest2.Items.Add(item2);
ddlTest2.Items.Add(item3);

ddlTest2.SelectedValue = "2";

Setting ddlTest2's selected value actually sets ddlTest as well since they share the same items list. If you run this bother ddlTest and ddlTest2 will have the exact same selected value even though only ddlTest2 was set.

Upvotes: 3

Paddy
Paddy

Reputation: 33867

Where is PleaseSelectItem declared? If you add the same instance of a listitem to many dropdownlists you are liable to get this problem.

Upvotes: 1

Related Questions