0

example of the gui

I am trying to get access to a button that is inside a user control which itself is inside another window. I have tried both the lines of code provided below.

Button manpanel = Application.OpenForms["STAFFHOMEMENU"].Controls["MASTERDATABASE"] as Button;
Button manpanel = Application.OpenForms["STAFFHOME"].Controls["MAINPANEL"].Controls["STAFFHOMEMENU"].Controls["MASTERDATABASE"] as Button;

Any fixes or alternative ways of accomplishing this would be great, Sorry if the message is a little unclear.

When the code is run with either of these lines I get the following error : "System.NullReferenceException: 'Object reference not set to an instance of an object."

drewpie
  • 21
  • 1
  • 7
  • So, what's wrong with what you have? – rory.ap Feb 02 '23 at 20:34
  • apologies I should have put that in the description, when running with either of the lines above I get the following error : System.NullReferenceException: 'Object reference not set to an instance of an object.' – drewpie Feb 02 '23 at 20:41
  • See the duplicate question, but I'm suspecting the issue is that your form names are wrong. If OpenFormns can't find the form with the given name, it will return null, and then you are trying to dereference properties on a null. – rory.ap Feb 02 '23 at 20:52
  • Alrighty then I'll have another look and see what I can do. – drewpie Feb 02 '23 at 20:57
  • OK an interesting update, I checked the names and they seem correct, I chucked a bit of code to check how many forms are open, ' int testing2 = Application.OpenForms.Count;' when run it gets back 2 which is equivalent to the number of forms open but does not include the user control that I am trying to access. Would there happen to be an opencontrol option instead of openform? – drewpie Feb 02 '23 at 21:05
  • Break it out into distinct steps. Here's a [Picture](https://pasteboard.co/ChVWPyeeOHri.png) to help you. Obviously change the names of the types to what you've got in your application. – Idle_Mind Feb 02 '23 at 21:07
  • It seems embarrassing that I didn't think to do it that way, ill have a bash and get back to you about it. – drewpie Feb 02 '23 at 21:09
  • 1
    ...and you can add `else` blocks on all of those `if` statements to let you know which part is returning `null` and causing your issue. – Idle_Mind Feb 02 '23 at 21:13
  • 1
    Followed your advice and put this in : UserControl user = MAINPANEL.Controls[0] as UserControl; Button button = user.Controls["MASTERDATABASE"] as Button; button.Enabled = false; button.BackColor= Color.Green; seems to work great – drewpie Feb 02 '23 at 21:56

0 Answers0