Send values from one form to another form

后端 未结 19 2895
眼角桃花
眼角桃花 2020-11-21 11:45

I want to pass values between two Forms (c#). How can I do it?

I have two forms: Form1 and Form2.

Form1 contains one button. When I click on that button, Fo

19条回答
  •  南旧
    南旧 (楼主)
    2020-11-21 12:01

    You can make use of a different approach if you like.

    1. Using System.Action (Here you simply pass the main forms function as the parameter to the child form like a callback function)
    2. OpenForms Method ( You directly call one of your open forms)

    Using System.Action

    You can think of it as a callback function passed to the child form.

    // -------- IN THE MAIN FORM --------
    
    // CALLING THE CHILD FORM IN YOUR CODE LOOKS LIKE THIS
    Options frmOptions = new Options(UpdateSettings);
    frmOptions.Show();
    
    // YOUR FUNCTION IN THE MAIN FORM TO BE EXECUTED
    public void UpdateSettings(string data)
    {
       // DO YOUR STUFF HERE
    }
    
    // -------- IN THE CHILD FORM --------
    
    Action UpdateSettings = null;
    
    // IN THE CHILD FORMS CONSTRUCTOR
    public Options(Action UpdateSettings)
    {
        InitializeComponent();
        this.UpdateSettings = UpdateSettings;
    }
    
    private void btnUpdate_Click(object sender, EventArgs e)
    {
        // CALLING THE CALLBACK FUNCTION
        if (UpdateSettings != null)
            UpdateSettings("some data");
    }
    

    OpenForms Method

    This method is easy (2 lines). But only works with forms that are open. All you need to do is add these two lines where ever you want to pass some data.

    Main frmMain = (Main)Application.OpenForms["Main"];
    frmMain.UpdateSettings("Some data");
    

    I provided my answer to a similar question here

提交回复
热议问题