how to return a value from main form to a differnt form or class(C#)

前端 未结 3 1006
慢半拍i
慢半拍i 2021-01-22 02:38

For some unknown reasons this silly thing cant be implemented.

I have an int count in the main form which I want to return to another class or form.

<
相关标签:
3条回答
  • 2021-01-22 03:00

    Where do you show the form? What you're doing is code is simply creating a new instance of the login form, and reading the nameCount value, which is still at its initialized value: 0.

    I think you should use ShowDialog and return the result in a DialogResult. If that's OK, then read the count value.

    0 讨论(0)
  • 2021-01-22 03:19

    This code will create a new instance of your Login form. Each instance will have its own instance variable count.

    login obj = new login();
    MessageBox.Show(obj.namecount().ToString());
    

    The default value for an integer is 0, so each time you create a new instance of the form it will have the value of 0 in the count variable. If you want to have all instances of the form have the same value for count, you should make count static.

    private static int count;
    

    When the variable is static, there will be only one instance of count shared by all instances of the Login form.

    var form1 = new login();
    // mouse up event fires on form1, value of count is set to 3 (for example)
    var form2 = new login();
    form2.namecount(); // returns 3
    

    Depending on what you want to do, there are other patterns, like using events, or a mediator that can help pass messages between components. This way when something happens in one form, other forms can react to the change without actually needing to reference or even know about the other forms in the application.

    0 讨论(0)
  • 2021-01-22 03:26
    private void button3_Click(object sender, EventArgs e)
    {
       login obj = new login();
       MessageBox.Show(obj.namecount().ToString());
    }
    

    Every time button3_Click is called, a new login object is instantiated. In other words, obj is not a reference to your main form; it is a reference to another object of the same type as your main form.

    Every time a login object is instantiated, count defaults to zero.

    0 讨论(0)
提交回复
热议问题