Search code examples
c#visual-studiowinformsuser-controlsvisual-studio-2019

Designer error when redirecting a button click within a custom user control


I've created a custom user control, that is essentially a custom button within my windows form app. I managed the redirect of the click event to using the following code:

Control[] customButtonControls = button.Controls.Find("buttonInUserControl", false);
Button nestedButton = (Button)customButtonControls[0];
nestedButton.Click += new System.EventHandler(this.button_click_handling_function);

I've appended this to the Window_Name.Designer.cs file below the generated code for the control with my button_click_handling_function being defined in my Window_Name.cs file.

The issue is that when I then click back to the Window_Name.cs[Design] page, I am met with an error page. I will include screen shots to better show the errors. Basically it is a super unhelpful page. It tells me that I have an index out of range error on my Array, but the stack call makes no sense.

If I try to build my Solution, I am met with NO compile errors and my program acts exactly as intended. The click event triggers the function just as before.

Thanks in Advance.

WinForms Error ScreenGrab


Solution

  • Portions of the designer code are run at design-time. The index out of range error is probably because at design-time there are no controls found yet by that Find call so the array is empty. You are not checking for 0 length so when you de-reference it you get the error. It works at run-time because at that point the controls have been instantiated.

    The secondary problem though is you should not put things into the Designer.cs files since that code is auto generated by the designer and could be regenerated at some point and your added code lost. Put that code in the Window_Name.cs after the InitializeComponent call.