C# 在C中向自定义对象的dropdownlist添加空项#

C# 在C中向自定义对象的dropdownlist添加空项#,c#,asp.net,C#,Asp.net,我们正在将自定义对象列表绑定到C#中的ASP.NET DropDownList,但我们希望允许DropDownList最初不选择任何内容。一种方法是创建一个中间字符串列表,用空字符串填充第一个列表,然后用自定义对象信息填充列表的其余部分 这看起来不太优雅,但是,有谁有更好的建议吗?是的,创建您的列表如下: <asp:DropDownList ID="Whatever" runat="server" AppendDataBoundItems="True"> <asp:Li

我们正在将自定义对象列表绑定到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("",""));
        }

事实上,这就是我目前所得到的(以及一些数据绑定的好东西)

第一:

DropDownList1.Items.Clear()

然后将listItems添加到dropDownList


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

这与我多年来一直使用的方式差不多,或者甚至不是在te DataBound中,但在设置数据源+1后的任何时间,这并不能真正回答问题,但是+1是因为当我刚开始使用ASP.NET时,我非常需要知道这一点,呵呵:)我花了几个小时才弄明白。知道了就简单了。谢谢,肖恩。不断赠送的礼物。:)
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);