views:

273

answers:

2

Hi,

I have a DropDown list which I Initialize in "CreateChildControls" and add to the controls collections. I then override the render method and then render the drop down list. The web part inherits from System.Web.UI.WebControls.WebParts.WebPart.

I bind the drop down list 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 selected index of the drop down list after the data bind, I get an error which says the control cannot have multiple selected items.

The code works fine, means that I can set the selected index after the data bind if I comment this line

//ddlClient.Items.Insert(0, PleaseSelectItem);

Can anyone give any explanation on why this would work.

Thanks

+1  A: 

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

Paddy
Yes, I am reusing the instance. Okay Let me try it without reusing the same instance.
iHeartDucks
+2  A: 
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.

Kelsey
What was bothering me was I never set the selected index to "PleaseSelectItem"... However, the selected index of the drop down list was always 0 and I was adding the list item at the index 0. So I guess it took it upon itself to set the selected index to 0. Yes, If I do not reuse the instance then the code works fine. Thanks. This has been a good lesson. So never reuse the instance across multiple drop down lists.
iHeartDucks
Oh, that makes sense. Thanks
iHeartDucks