在C#中将空项添加到自定义对象的下拉列表中

我们将自定义对象列表绑定到C#中的ASP.NET DropDownList,但我们希望允许DropDownList最初没有选择任何内容。 执行此操作的一种方法可能是创建一个中间字符串列表,使用空字符串填充第一个字符串,然后使用自定义对象信息填充列表的其余部分。

这似乎不是很优雅,但有没有人有更好的建议?

是的,像这样创建你的列表:

   

(注意使用AppendDataBoundItems="True"

然后在绑定时,绑定的项放在空项之后而不是替换它。

您可以添加到数据绑定事件:

 protected void DropDownList1_DataBound(object sender, EventArgs e) { DropDownList1.Items.Insert(0,new ListItem("","")); } 

实际上只是在研究这个,这是我到目前为止所得到的(以及几个数据绑定好东西)

 public interface ICanBindToObjectsKeyValuePair { void BindToProperties(IEnumerable bindableEnumerable, Expression> textProperty, Expression> valueProperty); } public class EasyBinderDropDown : DropDownList, ICanBindToObjectsKeyValuePair { public EasyBinderDropDown() { base.AppendDataBoundItems = true; } public void BindToProperties(IEnumerable bindableEnumerable, Expression> textProperty, Expression> valueProperty) { if (ShowSelectionPrompt) Items.Add(new ListItem(SelectionPromptText, SelectionPromptValue)); base.DataTextField = textProperty.MemberName(); base.DataValueField = valueProperty.MemberName(); base.DataSource = bindableEnumerable; base.DataBind(); } public bool ShowSelectionPrompt { get; set; } public string SelectionPromptText { get; set; } public string SelectionPromptValue { get; set; } public virtual IEnumerable ListItems { get { return Items.Cast(); } } } 

请注意,您可以做的一件事是

 dropDown.BindToProperties(myCustomers, c=>c.CustomerName, c=>c.Id); 

第一:

DropDownList1.Items.Clear();

然后将listItems添加到dropDownList。

这可以防止dropDownList每次在回发或异步回发中呈现时都获取不断增加的项目列表。