Tuesday, May 26, 2009

Drop Down List Common Functions

When programming for dropdownlists on my pages, I found that there are many ways to handle reseting the values in the boxes when populating them. I have used a for loop to check each value and set the value when it was found. However, this amounted to about 5 lines of code for each dropdownlist. I wrote these functions which I place in the CommonFunctions class which I include in each of my projects.  Here is the code:


#region SetDropDownByValue
public void SetDropDownByValue(System.Web.UI.WebControls.DropDownList dbo,
     string Value)

     for (int x = 0; x < dbo.Items.Count; x++) {
          if (dbo.Items[x].Value.Equals(Value)) { dbo.SelectedIndex = x; break; }
     }
}
#endregion 
#region SetDropDownByText
public void SetDropDownByText(System.Web.UI.WebControls.DropDownList dbo,
     string Text)
{
     for (int x = 0; x < dbo.Items.Count; x++) {
          if (dbo.Items[x].Text.Equals(Text)) { dbo.SelectedIndex = x; break; } 
     }
}
 #endregion



Using these functions saves me a number of lines of code and allows me to set dropdownlists by text or value depending on what data we have.

Enjoy!

No comments:

Post a Comment