• 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中有的值,可想而知就会出现异常,而采用第二中做法,就避免了这种异常!
  • 相关阅读:
    yum添加网易和搜狐源
    [置顶] 写代码更轻松——动软
    再看Core Data中PSC陷入死锁的问题
    【Android框架进阶〖0〗】ThinkAndroid注解机制
    MetaQ安装部署文档
    Android打开WIFI或者移动网络的代码实现
    设计模式简介
    补全状态码避免再去搜:
    onreadystatechange 事件
    服务器常用的状态码及其对应的含义如下:
  • 原文地址:https://www.cnblogs.com/xbf321/p/896051.html
Copyright © 2020-2023  润新知