Monday, March 28, 2011

Why is Me.components Nothing?

I have written a custom ErrorProvider which adds some functionality to the existing ErrorProvider (sets control BackColor, ErrorCount etc). This was working find but now for some reason it falls over on the constructor:

_LoginErrorProvider = New ErrorLogErrorProvider(Me.components)

The error is a NullReferenceException which is caused by the fact that Me.components is Nothing. Can anyone shed any light on why a form's components collection would be Nothing? The form seems to work fine in every other way!

From stackoverflow
  • Solved it, adding another component to the form seems to fix the problem, it's a bit of a cludge but works. I suppose the ideal solution would be to add my ErrorProvider to me.components but in order to do this you need to initialize a new instance which you can't because Me.components is Nothing!!

    It could drive a man crazy.....

  • when you add a component to the design surface it adds this in the InitializeComponent function

    me.components = new System.ComponentModel.Container()
    

    so just add this in your self.

    or your

    _LoginErrorProvider = New ErrorLogErrorProvider(Me.components)
    

    is being called before InitializeComponent

    Simon : I see, it was the Me.components initialisation I was missing!
  • You can also drop your ErrorLogErrorProvider class onto the design surface for your Form / UserControl and the code generated for InitializeComponent will correctly initialize the components member and pass it to the constructor of your error provider (VS does this for all non-visual components). Just make sure that your ErrorLogErrorProvider class derives from either Component or implements the IComponent interface.

    Simon : Good tip, I didn't know this.

0 comments:

Post a Comment