技术成就梦想

知道用户需求,做到专注!c#,donet,Frameworks,UML,面向对象,设计模式!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

DropDownList添加总结

Posted on 2009-08-15 11:47  我不是高手  阅读(562)  评论(0编辑  收藏  举报

在.net开发中常使用的DropDownList个人总结如下:

1.最常见的是手动添加控件Item,这里大家都会就不多说了。

2.还有一种是绑定DATETABLE的 个人感觉不错绑定分两种方式

e.g.: Private void FillCurrencyDDL()                                                                              

{

      DataTable dt = GetCurrencyDT();

      if(dt!=null)

           {

               foreach(DateRow row in dt.rows)

               {

                 this.ddl.Items.Add(new ListItem(row["Name"].ToString(),new Guid(row["ID"].ToString()).ToString())) //这里要求GetCurrencyDT()方法返回的值有Name和ID两项

               }

          }

}

另外一种绑定方法

DateSet ds = new DataSet();

ds = GetddlDateSet();

this.ddl.DataSource = ds.Table[0].DefaultView;

this.ddl.DataTextField ="name";

this.ddl.DataValueFiled="ID";

this.ddl.DataBind();

3.绑定已知的List

e.g. : //首先写一个LIST的方法

public static List GetList()

{

    List sCurrency = new List();

   sCurrency.Add("RMB");

   sCurrency.Add("USD");

   sCurrency.Add("JPY");

   Retrun sCurrency;

}

private void FillDDL()

{

    ValueList currencyList = this.ddl.ValueList;

    List sCurrencyList=GetDDL();

    foreach(string currency in sCurrencyList)

   {

         ValueListItem item =new ValueListItem(Currency);

         currencyList.ValueListItems.Add(item);

   }//此方法将DDL的Value和Text都会赋入一个值“Curreny”

   //这种方法一定要写在if(!IsPostBack){}中 否则选择后页面会始终重新加载,显示始终是第一项

}

4.另外附送一个年份的DDL控件写法 个人觉得还不错

public void FillDDL()

{

       List yearlist = new List();

       base.Items.Clare();

       if(IsNullable)

          base.Items.Add(new ListItem("AllYeas","0"));

       int todayYear = DateTime.Today.Year;

       for(int i=todayYear; i>=todayYear-9;i--)

       yearList.Add(i);//将从今年的前十年放入列表中

       base.DataSource = yearList;

      base.DataBind();

}