4

This is a follow-up to this question How to avoid repeated code?

I am using ASP.NET 4.0 with C# and I have a function called FillDropDownList(DropDownList ddl, DataTable dt, string dataValueField, string dataTextField, string defValue) which is called multiple times on one of my ASP.NET pages to populate some dropdown lists. I am now finding that I have several pages where I need to populate several dropdownlists in exactly the same way.

Rather than copying and pasting the same code in different pages, should I create a new class and put the method in that new class? How would I call it? What should I call the class? Should it have other functions in it? I was thinking maybe I should call it Util? What would you do?

Community
  • 1
  • 1
Mark Allison
  • 6,838
  • 33
  • 102
  • 151

1 Answers1

3

You can create static class and place there your function

public static class DropDownFiller
{
   public static void  FillDropDownList(DropDownList ddl, DataTable dt, string dataValueField, string dataTextField, string defValue)
   {
        /// bla bla
   }
}

Or you can create an extension to DropDownList (it is also a static class)

public static class DropDownListExtension
{
   public static void  FillDropDownList(this DropDownList ddl, DataTable dt, string dataValueField, string dataTextField, string defValue)
   {
        /// bla bla
   }
}

Usage (like method of DropDownList)

yourDropDownList.FillDropDownList(dataTable,valueField,textField,defValue);
Stecya
  • 22,896
  • 10
  • 72
  • 102