Showing posts with label Dropdownlist. Show all posts
Showing posts with label Dropdownlist. Show all posts

Monday, August 23, 2010

Check drop down list contains a value in c#

This is again a very simple post and want to share. I have seen many people write good coding, but, sometimes they don't pick efficient way to do somethings. When we do code reviews we can identify some code parts are very simple to implement but they implement it in complex way, want to correct them. A simple scenario is, how to check a drop down contains a value. Some people are looping through all items and finding the item exists or not. Some people are doing some complex logic etc. But, below is what I believe the good and simple way of finding a value is in drop down list of items.
if (ddlUserType.Items.FindByValue("someValue") != null)  
{  
   ddlUserType.SelectedValue = "someValue";  
} 
Do you think, is there any efficient way of doing this?

bind Enum to drop down list in ASP.NET

This the question asked by so many people around me and I also faced issues couple of times of my early stages of learning.This is simple but, how to get value and names as a collection and bind to drop down list is a bit difficult. Below is the simple logic to read all enums and create a list item and bind to drop down list. [There are many ways to get this done, but I believe below is the best way.]
foreach (UserType ut in Enum.GetValues(typeof(UserType)))
{
ListItem item = new ListItem(Enum.GetName(typeof(UserType), ut), ((int)ut).ToString("D"));
ddlUserType.Items.Add(item);
}
I think, you like this post. Let me know if you have any issues.