How can I pass values from one form to another?

前端 未结 10 2603
野的像风
野的像风 2020-12-02 00:43

Consider the situation where I have two windows forms, say F1 and F2. After using F1, I have now called F2.ShowDialog().

10条回答
  •  误落风尘
    2020-12-02 01:21

    Let's say you have a TextBox control in Form1, and you wish to pass the value from it to Form2 and show Form2 modally.

    In Form1:

    private void ShowForm2()
    {
        string value = TheTextBox.Text;
        Form2 newForm = new Form2();
        newForm.TheValue = value;
        newForm.ShowDialog();
    }
    

    In Form2:

    private string _theValue;
    public string TheValue 
    { 
        get
        {
            return _theValue;
        }
        set
        {
            _theValue = value; 
            // do something with _theValue so that it
            // appears in the UI
    
        }
    }
    

    This is a very simple approach, and might not be the best for a larger application (in which case you would want to study the MVC pattern or similar). The key point is that you do things in the following order:

    1. Create an instance of the form to show
    2. Transfer data to that new form instance
    3. Show the form

    When you show a form modally it will block the code in the calling form until the new form is closed, so you can't have code there that will transfer information to the new form in a simple way (it's possible, but unnecessarily complicated).

    [edit: extended the property methods in Form2 to be more clear]

提交回复
热议问题