Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

utility class vs subclassing .net controls

Tags:

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)

like image 461
toasteroven Avatar asked Jun 24 '09 13:06

toasteroven


1 Answers

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.

like image 59
Randolpho Avatar answered Oct 11 '22 17:10

Randolpho