Changing a label's text in another form in C#?

后端 未结 12 1539
日久生厌
日久生厌 2020-11-30 09:12

I have a label called LabelX1. This is on form2. On form1, i have a button. I want the button\'s text to be transferred to the other form\'s label. I have tried

<         


        
12条回答
  •  长情又很酷
    2020-11-30 09:29

    If you are needing to access the form2 from elsewhere in your code (like a button press for instance) you will not be able to see the instance of the form you create. To solve that I create a public instance to hold a reference to it like:

     public form2 form2_pub;
    

    Then after you create it you assign the new one to your public instance:

    form2 frm2 = new form2();
    frm2.Show();
    form2_pub = frm2
    

    Now you can reference form2_pub throughout your routines.

    Works for me at least.

    Remember, in your setter you can run whatever other code you want. For instance, I use the following to show what I want on another form by just setting show_scanning to true:

      public bool show_scanning //turns on the scanning screen
        {
            set
            {
                scanning_pnl.Visible = true;
                notReady_pnl.Visible = false;
                timer1.Enabled = true;
            }
        }
    

提交回复
热议问题