-3

I want to invoke a button click event automatically when the WPF form loads. So I'm calling it in the constructor right before initializeComponent();. But it always gives me the following error: System.NullReferenceException: 'Object reference not set to an instance of an object.'

the code is:

logoutBTN.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));

how can I fix this?

EDIT, SOLUTION This does the job! Thanks.

Loaded += (s, e) => logoutBTN.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Amateur24
  • 47
  • 6

2 Answers2

3

Short answer: You should place your code after the InitializeComponent() method.

Explanation: The InitializeComponent() method is where all the controls within your WPF class are instantiated. If you make any references to the controls before it, you would most likely get a null reference exception. See this article for more information.

Edit based on comment:

If this is the case you should only trigger this event after the page is fully loaded, you could register to the window's loaded event:

this.Loaded += (s, e) =>
        {
            logoutBTN.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
        };
VT Chiew
  • 663
  • 5
  • 19
  • This fixed my null reference exception! BUT, it looks like I can't initialize the button click because I get some interference with mysql connections. The button click get's an image from the database. But if I let the form initialize, and then clicking the button manually it loads perfectly. Maybe I should delay the automatic btn click? – Amateur24 May 04 '19 at 11:24
1

After InitialiseComponent(); Add:

this.Loaded+=new RoutedEventArgs(ButtonClickEvent);
bolkay
  • 1,881
  • 9
  • 20