DropDownList another way to set the selected item

Source: Internet
Author: User
In what we are doing according to a value, to compare all the values of the DropDownList, if the equality is selected, our usual practice is certainly:
Suppose we write the following code in the Click event of the button, which means that the current DropDownList selected value is written to the 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);
And then read it from the cookie in Page_Load, and if there is one in the cookie, the DropDownList in the protected void Page_Load is selected (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;
}
}

This is certainly true, and I'm going to talk about the following procedure:
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
; ;
}

}
}

}
Bold parts, this approach, although troublesome, but we think, if the first method, if the cookie is not empty, and, the value in the cookie is not DropDownList in the value, it is conceivable that there will be exceptions, and the second approach to avoid this anomaly.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.