在网站中会用到许多的下拉列表框,如果所有的数据都从数据库读取,就会影响页面的加载速度,我这里用后台手动添加的数据填充dropdownlist;

原理:循环为dropdownlist的listitem项赋值;

代码如下:

namespace WebApplication1.DAL
{
    public class ServiceManager
    {

    //defaultValue 下标,defaultText 默认显示值
        public   void BindDictionaryToDrop(Dictionary<int, string> dicInfo, WebControl control, string defaultValue, string defaultText)
        {
            List<ListItem> listItem = new List<ListItem>();
            listItem.Add(new ListItem(defaultText, defaultValue));
            foreach (var a in dicInfo.Keys)
            {
                ListItem item = new ListItem()
                {
                    Text = dicInfo[a],
                    Value = a.ToString()
                };  
                listItem.Add(item);
            }
            (control as DropDownList).Items.AddRange(listItem.ToArray());
           


        }
        public enum StartCity{
              Default,
              /// <summary>
              /// 上海
              /// </summary>
              ShangHai=1,
              BeiJing=2,
              HuNan=4
        }
        public Dictionary<int, string> SUBSTATION = new Dictionary<int, string>() {
            { (int)StartCity.ShangHai,"上海站"},
            { (int)StartCity.BeiJing,"北京站"},
            { (int)StartCity.HuNan,"湖南站"},
        };
    }
}

 

方法调用:

namespace WebApplication1.Order
{
    public partial class OrderList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ServiceManager ss = new ServiceManager();
            ss.BindDictionaryToDrop(ss.SUBSTATION,this.DropDownList1,"0","请选择");
        }
    }
}

 

如有补充,多谢指导!

posted on 2017-02-28 10:09  cunese初见  阅读(409)  评论(0)    收藏  举报