Derive or subclass a WinForm Datagrid or other control in .NET

A cool feature of .NET is that you can derive a new control from an existing control and your new control inherits all the features and functionality of the original. You can then subclass your control by adding new properties and methods and override existing methods to alter their behavior.

So how do you derive a control and use it in your project? Follow these steps which derive a new DataGrid:

  1. Add a new class to your project: right click the project name in the Solution Explorer and select Add Class from the Add menu.

  2. Choose Class from the Templates Panel and name it MyDataGrid.

  3. In MyDataGrid's code window add the following:

    In VB.NET add:

    Inherits Windows.Forms.DataGrid to the Declarations section.

    With C#, change the declaration of your derived class to:

    public class MyDataGrid : System.Windows.Forms.DataGrid

  4. Add any other code to subclass the grid as required.

To use MyDataGrid on your form in VB.NET:

  1. View your form's code and expand the Windows Form Designer generated code region.

  2. Add the line: Friend WithEvents DataGrid As MyDataGrid where the other Friend... statements are located.

    The line for the standard DataGrid would look like:
    Friend WithEvents DataGrid As System.Windows.Forms.DataGrid.

  3. Locate the line: Private Sub InitializeComponent() and add Me.DataGrid = New YourProjectName.MyDataGrid where YourProjectName is the actual name of your project.

    Again, the line for the standard datagrid looks like:
    Me.DataGrid = New System.Windows.Forms.DataGrid.

To use MyDataGrid on your form in C#:

  1. View your form's code and change the line that looks like:

    private System.Windows.Forms.DataGrid myDataGrid;


    private DataGridEx myDataGrid;

  2. Locate the line: private void InitializeComponent() and within that routine replace

    this.dataGrid = new System.Windows.Forms.DataGrid();


    this.myDataGrid = new YourProjectName.DataGridEx();

    where YourProjectName is the actual name of your project.

To add an icon for your derived DataGrid on the toolbox:

  1. Derive a new grid as described above. Save and compile your project.

  2. Open any form and view it in Design mode so the toolbox is visible.

  3. Right click the toolbox and select Add/Remove Items....

  4. On the .NET Framework Components tab Browse to your project's executable in the Bin folder.

  5. Click Open then OK to add your control to the toolbox.

  6. You can now drag your derived datagrid onto a form.

About TheScarms
About TheScarms

Sample code
version info

If you use this code, please mention ""

Email this page

© Copyright 2024 TheScarms
Goto top of page