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中有的值,可想而知就会出现异常,而采用第二中做法,就避免了这种异常!
原文地址:https://www.cnblogs.com/xbf321/p/896051.html