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

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

ContractedBlock.gifExpandedBlockStart.gif Code
            DropDownList1.DataSource = Enum.GetNames(typeof(YSMV.XWShop1B2C.Model.OrderStatus));
            DropDownList1.DataBind();

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

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

ContractedBlock.gif ExpandedBlockStart.gif Code
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控件的方法为例,关键在于设置第一项的值为空,那如何设置呢?

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

 

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

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

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

 

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

转载于:https://www.cnblogs.com/4inwork/archive/2009/02/19/1393970.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值