我们正在使用C#将自定义对象列表绑定到ASP.NET DropDownList,但是我们希望允许DropDownList最初没有选择任何内容。一种方法是创建一个字符串的中间列表,用空字符串填充第一个,然后用自定义对象信息填充其余部分。
然而,这种方法似乎不太优雅,有没有更好的建议?
然而,这种方法似乎不太优雅,有没有更好的建议?
是的,你可以这样创建列表:
<asp:DropDownList ID="Whatever" runat="server" AppendDataBoundItems="True">
<asp:ListItem Value="" Text="Select one..." />
</asp:DropDownList>
(请注意使用 AppendDataBoundItems="True"
)
然后当您绑定数据时,绑定的项会被放置在空项之后,而不是替换它。
protected void DropDownList1_DataBound(object sender, EventArgs e)
{
DropDownList1.Items.Insert(0,new ListItem("",""));
}
我正在处理这个问题,以下是目前的进展情况(以及一些数据绑定的技巧)。
public interface ICanBindToObjectsKeyValuePair {
void BindToProperties<TYPE_TO_BIND_TO>(IEnumerable<TYPE_TO_BIND_TO> bindableEnumerable, Expression<Func<TYPE_TO_BIND_TO, object>> textProperty, Expression<Func<TYPE_TO_BIND_TO, object>> valueProperty);
}
public class EasyBinderDropDown : DropDownList, ICanBindToObjectsKeyValuePair {
public EasyBinderDropDown() {
base.AppendDataBoundItems = true;
}
public void BindToProperties<TYPE_TO_BIND_TO>(IEnumerable<TYPE_TO_BIND_TO> bindableEnumerable,
Expression<Func<TYPE_TO_BIND_TO, object>> textProperty, Expression<Func<TYPE_TO_BIND_TO, object>> 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<ListItem> ListItems {
get { return Items.Cast<ListItem>(); }
}
}
dropDown.BindToProperties(myCustomers, c=>c.CustomerName, c=>c.Id);
首先:
DropDownList1.Items.Clear();
然后将listItems添加到dropDownList中。
这可以防止dropDownList在每次回发或异步回发时获取越来越多的项目列表。