zoukankan      html  css  js  c++  java
  • DropDownList又一种设为被选择项的办法

        在我们在做根据一个值,来和DropDownList的所有值对比,如果相等则选中一项,我们通常的做法肯定是:
    假如我们在Button的Click事件中写如下的代码,也就是把当前DropDownList选中的值写入Cookie中,
        protected void Button1_Click(object sender, EventArgs e)
        {
            HttpCookie hc 
    = new HttpCookie("InterfaceStyle"this.DropDownList1.SelectedValue);
            hc.Expires 
    = DateTime.Now.AddMonths(1);
            Response.Cookies.Add(hc);
        }
    然后在Page_Load中在从Cookie中读出来,如果Cookie中有的话,则该DropDownList中的莫一项选中
        protected void Page_Load(object sender, EventArgs e)
        {
            
    if (!Page.IsPostBack)
            {
                NameValueCollection nvc 
    = (NameValueCollection)ConfigurationManager.GetSection("interfaceStyle");

                
    for (int i = 0; i < nvc.Count; i++)
                {
                    
    this.DropDownList1.Items.Add(new ListItem(nvc[nvc.GetKey(i)], nvc.GetKey(i)));
                }
                HttpCookie hc 
    = Request.Cookies["InterfaceStyle"];
                
    if(hc != null)
                {

                    this.DropDownList1.SelectedValue = hc.Value;
                }
            }
            
        }
     这种做法肯定也是正确的,而我要讲的事下面的一中做法:
        protected void Page_Load(object sender, EventArgs e)
        {
            
    if (!Page.IsPostBack)
            {
                NameValueCollection nvc 
    = (NameValueCollection)ConfigurationManager.GetSection("interfaceStyle");

                
    for (int i = 0; i < nvc.Count; i++)
                {
                    
    this.DropDownList1.Items.Add(new ListItem(nvc[nvc.GetKey(i)], nvc.GetKey(i)));
                }
                HttpCookie hc 
    = Request.Cookies["InterfaceStyle"];
                
    if(hc != null)
                {
                    ListItem li 
    = this.DropDownList1.Items.FindByValue(hc.Value);
                    
    if(li != null
    )
                    {
                        li.Selected 
    = true
    ; ;
                    }

                }
            }
            
        }

             黑体加粗部分,这种做法虽然麻烦,可是我们想一想,如果采用第一种方法的时候,假如Cookie不为空,而且,Cookie中的值也不是DropDownList中有的值,可想而知就会出现异常,而采用第二中做法,就避免了这种异常!
  • 相关阅读:
    9.19题解
    9.18题解
    改码风
    找到了几个好的网站
    题目链接
    二分上机训练题解
    二分例题简单说明
    贪心上机训练题解
    贪心算法例题简单说明
    Johnson法则证明
  • 原文地址:https://www.cnblogs.com/xbf321/p/896051.html
Copyright © 2011-2022 走看看