Changing values of another form from a separate form (solution not working)

前端 未结 2 782
小蘑菇
小蘑菇 2021-01-25 18:12

peoples. Today I\'m attempting to change the background image of a panel from a separate form. I\'ve looked at a few S.O. questions and they have all said to create a new form

相关标签:
2条回答
  • 2021-01-25 18:52

    You have to change the variable in the specific instance of the form that you want to change. I would recommend adding the form as a parameter of your method or convert your static method to an extension method.

    Parameter:

    public static void changeGridSize(Form_Main frm, int newSize)
    {
        switch (newSize) 
    

    Extension Method:

    public static void changeGridSize(this Form_Main frm, int newSize)
    {
        switch (newSize)
    

    Usage of the extension method would be from the calling form:

    myFormMain.changeGridSize(newSize);
    
    0 讨论(0)
  • 2021-01-25 18:54

    Your "other" form needs an instance of the main form (Form_Main), which you have stored as a variable named frm. With this variable you can call the main form instance, like this:

    frm.changeGridSize(newSize);
    

    Instead you are trying to call the form like it is a static class by using the syntax:

    Form_Main.changeGridSize(newSize);
    

    To get the instance of the main form to the "other" form, you can pass it to the constructor of the other form, like this:

    public class OtherForm : Form
    {
        Main_Form _mainForm;
    
        // Constructor
        public OtherForm(Main_Form theMainForm)
        {
            _mainForm = theMainForm;
        }
    
        public static void changeGridSize(int newSize)
        {
            _mainForm.changeGridSize(newSize);
        }
    }
    

    Finally, when you are creating your "other" form, you will need to pass an instance of the main form, like this:

    OtherForm theOtherForm = new OtherForm(this);
    
    0 讨论(0)
提交回复
热议问题