Detecting if your control is being created

Some properties are only valid when compared to other properties. During initialization it is logical to allow invalid properties. This is how to check if your control is being initialized.

Take for example a control which has Minimum, Maximum, and Value properties (Int32).

Logic states that Minimum must not be greater than the Maximum, and that Value must be within the range Minimum..Maximum. If an attempt is made to set a property to an illogical value you might want to raise an exception.

The problem is that as a component writer you have no control over which order the user sets / changes properties, and may end up with an initialization section which looks like this:

  myControl1.Value = 1000;
  myControl1.Maximum = 2000;
  myControl1.Minimum = 500;

if the default values for the control are Minimum=0, Maximum=10, Value=0 then it is quite obvious that the first line which sets Value to 1000 will cause an error.

To overcome this problem you can use the ISupportInitialize interface. For example.....

public MyControl: Control, ISupportInitialize
  Boolean isInitializing = false;
  Int32 minimum = 0;
  Int32 value = 0;
  Int32 maximum = 10;

  void ISupportInitialize.BeginInit()
    isInitializing = true;

  void ISupportInitialize.EndInit()
    isInitializing = false;

  public Int32 Minimum
    get {return minimum;}
      if (!isInitializing)
        Do your validation here
      minimum = value;

The .NET framework will check each component for ISupportInitialize before setting its properties, and if supported will perform the following

...set properties of component...


Share this article!

Follow us!

Find more helpful articles: