0

My code creates multiple forms at runtime. These forms are populated with multiple controls read from a text file. What I'm also trying to do is create actions for the controls based on another text file.

The text file follows this template:

ActionToPerform=(control)(trigger)(settings)

The problem I have is that this happens in a loop and as such the event listener seems to lose scope. The control to put the event on is found by searching for controls on the current form with the same name as in the settings file.

This is an example of my event listener code:

myForms[locali].Controls.Find(actionObject, false).FirstOrDefault().MouseDown += new MouseEventHandler(myForms[locali].SendEmail_Event);

But I get the error 'object reference not set to an instance of an object'.

How can I rewrite the code to allow me to add the events to the right controls using the settings in the file?

Chrayfish
  • 157
  • 2
  • 11
  • Without seeing what is not working we could only guess at what will work. Please include short code to show the failure. – Richard Jun 09 '15 at 09:28

1 Answers1

1

It is possible that FirstOrDefault returns null. So check if it is null or not before use it

var obj= myForms[locali].Controls.Find(actionObject, false).FirstOrDefault();
if(obj!=null){
    obj.MouseDown += new MouseEventHandler(myForms[locali].SendEmail_Event);
}
Manish Parakhiya
  • 3,732
  • 3
  • 22
  • 25
  • Hi @Manish, it is returning null. I am left wondering why though, the settings file for controls is ran through first. There is an entry creating a button with the right name and the code does add it to the parent form. – Chrayfish Jun 09 '15 at 09:53