假如我们在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);
}
{
HttpCookie hc = new HttpCookie("InterfaceStyle", this.DropDownList1.SelectedValue);
hc.Expires = DateTime.Now.AddMonths(1);
Response.Cookies.Add(hc);
}
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;
}
}
}
{
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; ;
}
}
}
}
{
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中有的值,可想而知就会出现异常,而采用第二中做法,就避免了这种异常!