简体   繁体   English

绑定下拉列表然后添加新的列表项

[英]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. 我有一个DropDownList ,我在一个名为CreateChildControls的函数中初始化它,然后将它添加到Controls集合中。 I then override the Render() method and then render the DropDownList . 然后我重写Render()方法,然后渲染DropDownList The web part inherits from System.Web.UI.WebControls.WebParts.WebPart . Web部件继承自System.Web.UI.WebControls.WebParts.WebPart

I bind the DropDownList in my web part like this: 我在我的Web部件中绑定DropDownList ,如下所示:

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. 如果我在调用DataBind之后尝试设置DropDownListSelectedIndex ,我会收到一个错误,指出控件不能有多个选定项。

That code works fine, and I can set the SelectedIndex after the data bind if I comment out this line: 该代码工作正常,如果我注释掉这一行,我可以在数据绑定后设置SelectedIndex

ddlClient.Items.Insert(0, PleaseSelectItem);

Can anyone explain why this wouldn't work? 任何人都可以解释为什么这不起作用?

Thanks. 谢谢。

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. 当你设置'selected'属性时,你将它设置为ListItem的实例,所以如果你有更多的ListItems你正在重用,那么它们将获得相同的值,这可能会导致你遇到的问题。

To illustrate the problem see this example with 2 dropdownlists: 为了说明问题,请参阅此示例,其中包含2个下拉列表:

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. 设置ddlTest2的选定值实际上也设置了ddlTest,因为它们共享相同的项列表。 If you run this bother ddlTest and ddlTest2 will have the exact same selected value even though only ddlTest2 was set. 如果你运行这个麻烦ddlTestddlTest2将具有完全相同的选定值,即使只设置了ddlTest2

Where is PleaseSelectItem declared? PleaseSelectItem在哪里宣布? If you add the same instance of a listitem to many dropdownlists you are liable to get this problem. 如果将listitem的同一实例添加到许多下拉列表中,则可能会出现此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM