views:

148

answers:

3

I want to reuse some code I wrote to add some functionality to a datagridview. I want the default datagridview properties and events to be exposed, so I didn't want to create a new custom component. so I tried writing a subclass, which works fine. but it also occurred to me that I could write a standalone utility class that takes a datagridview in the constructor and sets it up the same way. e.g.

public class
MyGrid
{
    private DataGridView m_dg;

    public MyGrid(DataGridView dg)
    {
        m_dg = dg;
        m_dg.RowHeadersVisible = false;
        m_dg.SortCompare += new DataGridViewSortCompareEventHandler(m_dg_SortCompare);
    }

    void m_dg_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
    {
        // do custom sorting here
    }
}

so somewhere in my app's startup I would call

MyGrid g1 = new MyGrid(dataGridView1);
MyGrid g2 = new MyGrid(dataGridView2);

and so forth. any disadvantages to this approach? it seems like much of the code is going to be the same, the difference is between how you instantiate the extended grid (drag and drop a subclassed control to the form vs drag a plain datagridview and call the above code)

+3  A: 

In the long run, a utility class will be more maintainable than a subclassed control unless you are doing something more substantial to extend DataGridView than modifying sorting.

Your approach for the utility class (taking a DataGridView in the constructor) is a solid approach.

Randolpho
+1  A: 

The only disadvantage of a utility class, is that you lose the designer support. Meaning, if you subclass the control, when you add it to the designer, any changes you make in the constructor of your inherited control will show up in the designer. Furthermore, if you want to add some properties to it, they will show up in the properties window, giving it even more flexibility. If designer support doesn't matter to you though, then I don't see any other drawbacks to a utility class.

BFree
+1  A: 

If you're using C# 3, extension methods might be worth a look. Looks like you're adding behavior to a type, that you wished existed out of the box.

static class GridExtMethods
    {
        public static void SortAsICommand(this MyGrid grid)
        {
            //grid.Prop = value; possible
            grid.Sort += MyCustomSort;
        }
        static void MyCustomSort(object sender, SortEventArgs evtArgs)
        {
            Console.WriteLine("Sort {0} and {1}", evtArgs.First, evtArgs.Second);
        }
    }

....

static void Main()
{
   var grid = new MyGrid(10,20);
   grid.SortAsICommand();

   //grid.RaiseEvent(); do something that raises the event
}
Gishu