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

时间:2009-03-24 20:31:38

标签: c# asp.net

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

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

4 个答案:

答案 0 :(得分:23)

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

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

(请注意使用 AppendDataBoundItems="True"

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

答案 1 :(得分:11)

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

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

答案 2 :(得分: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);

答案 3 :(得分:1)

首先:

DropDownList1.Items.Clear();

然后将listItems添加到dropDownList。

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