0

I am trying to define an object in one form, and then when the user clicks a button, the object will be added to a new form that shows.

Form 1

Public Shared label As New Label

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    label.Text = "test"
End Sub

Form 2

Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.Controls.Add(Form1.label)
End Sub

Whenever I run this, it does not put the label on the second form. Can anyone tell me what I am doing wrong, or show a better way of doing this?

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
Yek
  • 1
  • Does this answer your question? [Communicate between two windows forms in C#](https://stackoverflow.com/questions/1665533/communicate-between-two-windows-forms-in-c-sharp) – Peter Duniho May 19 '21 at 20:27
  • Without a proper [mcve], it's not possible to say what exactly is wrong with your code. But it is possible to point out that the entire approach is really, really wrong. A given `Form` class should be entirely in charge of its own children; no other object should be involved, and the children objects should all be 100% private to the form. The correct approach in your example would be for the `Form2` class to already have the `Label` ... – Peter Duniho May 19 '21 at 20:30
  • ... (preferably added via the Designer), and to expose a `string` property that allows `Form1` to set the `Text` property at the appropriate time. The proposed duplicate provides plenty of detail into different ways to approach that basic idea. – Peter Duniho May 19 '21 at 20:30
  • 2
    Code works as posted. It's unusual to try to move controls like that. You should favor moving data instead. – LarsTech May 19 '21 at 20:31
  • 1
    You would probably be much better served by creating a new instance of a label on your second form – Hursey May 19 '21 at 20:35
  • @LarsTech Good idea, I will try doing that instead – Yek May 19 '21 at 20:46

0 Answers0