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中有的值,可想而知就会出现异常,而采用第二中做法,就避免了这种异常!
  • 相关阅读:
    java学习笔记——基于Robot类的屏幕分享
    Java实例——基于jsoup的简单爬虫实现(从智联获取工作信息)
    Java实例练习——基于UDP协议的多客户端通信
    java实例练习——基于TCP/IP协议的多客户端通信
    我个人的Java学习经验(一家之言)
    PHP mac localhost 环境下发送邮件
    php ob_start()、ob_end_flush和ob_end_clean()多级缓冲
    php ob_start()、ob_end_flush和ob_end_clean()多级缓冲
    程序员应该知道的13个设计技巧
    程序员应该知道的13个设计技巧
  • 原文地址:https://www.cnblogs.com/xbf321/p/896051.html
Copyright © 2011-2022 走看看