Fill a dropdownlist with a range of numbers in single line


We all have to create dropdownlists which contains a range of values, may be days in a month 1 to 31 or may be years like 2013 to and what we always do ? will write a for loop everywhere we need this. I am presenting you an extension method for dropdownlist to simplify this

We all have to create dropdownlists which contains a range of values, may be days in a month 1 to 31 or may be years like 2013 to and what we always do ? will write a for loop everywhere we need this. I am presenting you an extension method for dropdownlist to simplify this. If we have this control extension in our application, you just need a single line to bind a range of integer values to a drop down list. Lets see the code now


///
/// Fills a dropdownlist with numbers according to range specified
///

/// Dropdownlist to be filled
/// starrting value
/// ending value
/// incrementing value
/// do we need to add a default "select" item
/// if you do not need "select" specify default text
public static void FillNumbers(this DropDownList ddl, int start, int end, int seed, bool includeSelect, string defaultText)
{
ddl.Items.Clear();

if (start > end)
{
for (int i = start; i >= end; i = i - seed)
{
ddl.Items.Add(i.ToString());
}
}
else
{
for (int i = start; i <= end; i = i + seed)
{
ddl.Items.Add(i.ToString());
}
}

if (includeSelect)
{
string selecttext = "-Select-";
if (!string.IsNullOrEmpty(defaultText))
selecttext = defaultText;
ddl.Items.Insert(0, new ListItem(selecttext, "0"));
}
}


As you can see the code will automatically identify if the range should be added ascending or descending. To make it much simple we can use some overloading also


public static void FillNumbers(this DropDownList ddl, int start, int end, int seed, bool includeSelect)
{
FillNumbers(ddl, start, end, seed, includeSelect, "");
}
public static void FillNumbers(this DropDownList ddl, int start, int end, int seed)
{
FillNumbers(ddl, start, end, seed, false, "");
}
public static void FillNumbers(this DropDownList ddl, int start, int end)
{
FillNumbers(ddl, start, end, 1, false, "");
}


Hope you like it. Let me know if you have questions. Happy Coding :)


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: