Saturday, April 4, 2015

ASP.Net C# Extension Method to select item in DropDownList

Here's another extension method that's part of my standard extension library. It simply selects an item in a DropDownList. Why bother with an extension method you ask? Mainly to keep from having to check if the item exists in the dropdown and also so you don't have to worry about if an item is already selected (e.g. Cannot have multiple items selected in a DropDownList.)

Code:
 public static void SetValue(this DropDownList control, string value)  
 {  
      // variables  
      var ListItem = control.Items.Cast<ListItem>().Where(x => x.Value.IsEqual(value)).FirstOrDefault();  
   
      // check for match  
      if (ListItem != null)  
      {  
           control.ClearSelection();  
           ListItem.Selected = true;  
      }  
 }  

Example usage:
 ddlState.SetValue(State);  

Dependencies:

The SetValue extension method is dependent on the IsEqual extension method previously discussed.

This same technique can also be applied to the HtmlSelect control.
 public static void SetValue(this HtmlSelect control, string value)  
     {  
       // variables  
      var ListItem = control.Items.Cast<ListItem>().Where(x => x.Value.IsEqual(value)).FirstOrDefault();  
   
       // check for match  
       if (ListItem != null)  
       {  
         ListItem.Selected = true;  
       }  
     }  

0 comments: