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)
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.