下拉列表框DropDownList绑定Dictionary泛型类

DropDownList绑定Dictionary泛型类

定义一个Dictionary泛型类

/// <summary>
    /// 产品类型
    /// </summary>
    /// <returns></returns>
    public Dictionary<string, string> productType()
    {
        Dictionary<string, string> d = new Dictionary<string, string>();
        d.Add("-1", "产品类型");
        d.Add("1", "白酒");
        d.Add("2", "啤酒");
        d.Add("3", "葡萄酒");
        d.Add("4", "保健酒");
        d.Add("5", "洋酒");
        d.Add("6", "黄果米酒");
        return d;
    }

DropDownList1绑定Dictionary泛型类作为数据源:

DropDownList1.DataSource = productType();
DropDownList1.DataTextField = "value";
DropDownList1.DataValueField = "key";
DropDownList1.DataBind();
Label1.Text = productType()["3"].ToString() + "__" + productType()["5"].ToString() ;//获取其中的某个值

查了一下网上基本都是这种简单的例子:

如果需要绑定一个对象:采用如下方式,

Dictionary<int,Customer> customerDic=由自定义的函数返回;

那么,dropdownlist控件数据源应该设置为:

customerDic.values,

其他两项设置需要绑定的对应的字段即可。

原文地址:https://www.cnblogs.com/yuhuameng/p/5038379.html