Saturday, October 17, 2009

Why and How to Sub-class Base Classes

One of the “basic rules of programming” that I always live by (and I’m not alone), is that one should always sub-class many of the native base class controls.  This is one of the first things you should do before undertaking any serious development, in any language. There are always little quirks in behavior in some of the base class controls  that you want to get around for every instance of an object.

Say, as an example, that you've developed a few forms for your application. You've used the base class controls. At some point, you find something's not  quite acting right and you want to change that behavior or you may just want to add something (some properties or something) to every ComboBox, for example, that you use. Now, since you used the base class controls to begin with ... guess what? You've outta luck!! You've got a lot of work ahead of you to change all those. Whereas, if you had sub-classed all the controls first (even if you haven't as yet put code in those sub-classes) and used your sub-classed controls on your forms, then you'll have no extra work to do when you decide that you need to make changes to your sub-classed control (and yes, even the form should be sub-classed).

Basically, you'll want a class library that contains your sub-classed UI controls, like textbox, button, etc. Something like this:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace MyCompany.MyFramework.WinUI.MyClasses
{
public class MyComboBox : System.Windows.Forms.ComboBox
{
// code here
}

public class MyTextBox : System.Windows.Forms.TextBox
{
// code here
}

public class MyButton : System.Windows.Forms.Button
{
// code here
}
}

That's it. These controls can't be sub-classed visually, but as you can see, it's easy enough to do it in code. I have all the basic controls sub-classed in one class library file. Once they're added to the ToolBox, then can be dragged onto any design surface in the IDE.

4 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Spoke too soon, eh Marc? ;0)

    ReplyDelete
  4. You have given this great idea for (eg):
    Can you show an example: MyTextBox which would be located within the Mygrid and who would do the following: how I type in MyTextBox, so the search is executed in column in which is located the MyTextBox (eg searching binding source)?
    Thanks

    ReplyDelete