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

6
我们正在使用C#将自定义对象列表绑定到ASP.NET DropDownList,但是我们希望允许DropDownList最初没有选择任何内容。一种方法是创建一个字符串的中间列表,用空字符串填充第一个,然后用自定义对象信息填充其余部分。
然而,这种方法似乎不太优雅,有没有更好的建议?
4个回答

23

是的,你可以这样创建列表:

<asp:DropDownList ID="Whatever" runat="server" AppendDataBoundItems="True">
    <asp:ListItem Value="" Text="Select one..." />
</asp:DropDownList>

(请注意使用 AppendDataBoundItems="True"

然后当您绑定数据时,绑定的项会被放置在空项之后,而不是替换它。


简单易懂,只要你知道了。谢谢Sean。这是一份不断给予的礼物。 :) - BobRodes

11
您可以在databound事件中添加以下内容:
protected void DropDownList1_DataBound(object sender, EventArgs e)
        {
            DropDownList1.Items.Insert(0,new ListItem("",""));
        }

这基本上是我多年来一直在做的方式,或者甚至不仅限于DataBound,而是在设置了DataSource之后的任何时间+1。 - Christopher Klein

2

我正在处理这个问题,以下是目前的进展情况(以及一些数据绑定的技巧)。

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);

1

首先:

DropDownList1.Items.Clear();

然后将listItems添加到dropDownList中。

这可以防止dropDownList在每次回发或异步回发时获取越来越多的项目列表。


这并没有真正回答问题,但是+1,因为当我刚开始使用ASP.NET时,我非常需要知道这个,呵呵 :) 我花了几个小时才弄明白。 - SirDemon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接