基本控件使用技巧之--DropDownList数据绑定


 1.将Enum绑定到DropDownList控件的方法

            DropDownList1.DataSource = Enum.GetNames(typeof(YSMV.XWShop1B2C.Model.OrderStatus));
            DropDownList1.DataBind();

   将Enum绑定到DropDownList控件的主要用到Enum的是GetNames(),该方法得到的是一个Enum名称的数组string[],当然你也可以使用GetValues()获得Enum的数值。由此可见该绑定实际是将DropDownList绑定到一个数组。

  2.将对象List<T>绑定到DropDownList控件的方法

1            DropDownList3.DataSource = (new YSMV.XWShop1B2C.BLL.Logistics().GetAll());
2             DropDownList3.DataTextField = "Name";
3             DropDownList3.DataValueField = "Name";
4             DropDownList3.DataBind();

   new YSMV.XWShop1B2C.BLL.Logistics().GetAll()方法获得一个List<LogisticInfo>,绑定的关键在于设置DropDownList的DataTextField ,DataValueField,name便是 LogisticInfo的field.

  3.DropDownList数据绑定第一项为空的方法

  以将对象List<T>绑定到DropDownList控件的方法为例,关键在于设置第一项的值为空,那如何设置呢?

  我们可以直接设置第一项为空,如下

            DropDownList3.DataSource = (new YSMV.XWShop1B2C.BLL.Logistics().GetAll());
            DropDownList3.DataTextField = "Name";
            DropDownList3.DataValueField = "Name";
            DropDownList3.DataBind();
            DropDownList3.Items[0].Text = "";
            DropDownList3.Items[0].Value = "";

  这么做是将第一项设置为空了,但是原来第一项的内容没有了,那来此法不可取。于是想到了再第一项的位置插入一个空相,代码:

1             DropDownList3.DataSource = (new YSMV.XWShop1B2C.BLL.Logistics().GetAll());
2             DropDownList3.DataTextField = "Name";
3             DropDownList3.DataValueField = "Name";
4             DropDownList3.DataBind();
5             DropDownList3.Items.Insert(0, new ListItem());

  末,其他绑定方法我将继续添加,请关注


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3