Tuesday, July 13, 2010

How to set Selected item to a DropDownList (asp.net) & Other DropDown List Goodies.

1. Code below will set the (passed DB) value as the selected item in the drop downlist.

//database passes the value q1

            if (!string.IsNullOrEmpty(q1))
            {
            
// checks if the selected item is in the drop downlist (and which index no)
              int selIndex = ddlQuestions.Items.IndexOf(ddlQuestions.Items.FindByValue(q1.Trim()));
           
//if the above cant find the item in dropdown list means, item do not exist and -1 is return
                if(selIndex == -1)
                {
                ddlQuestions.SelectedIndex = 0;                    
                }
                ddlQuestions.SelectedIndex = selIndex;
            }


2. Best way to populate a Drop Down List, Use (sortedList), its better then hashTable as the list will be ordered.

//Setup Sorted List
SortedList sl = new SortedList();
            sl.Add(0,"No Access");
            sl.Add(1, "Guest");
            sl.Add(2, "User");
            sl.Add(9, "Admin");

//Bind sortedList to drop down list
        ddlPermission.DataSource = sl
        ddlPermission.DataTextField = "value";
        ddlPermission.DataValueField = "key";
        ddlPermission.DataBind();


3. How to lookup value by key in the sorted list

            permission = Convert.ToInt32(Eval("Permission").ToString().Trim());
            int index = sl.IndexOfKey(permission);
            return sl.GetByIndex(index).ToString();


No comments: