c# add label from form2

前端 未结 2 1744
清歌不尽
清歌不尽 2020-12-22 13:56

Form2 code:

public void button2_Click(object sender, EventArgs e)
        {   
          Form1 form1form = new Form1();
            Label asd = new Label();
         


        
2条回答
  •  旧巷少年郎
    2020-12-22 14:46

    If you want to access form1form from form2form you must have public reference to form1form. Declare property in form1form like below:

    public static form1form Instance { get; private set; }
    

    Then set Instance in Load event of form1form:

    private void form1form_Load(object sender, EventArgs e)
    {
       Instance = this;
    }
    

    In form2form:

    public void button2_Click(object sender, EventArgs e)
    {
        Label asd = new Label();
        asd.Text = "asdasasdasdasd";
        form1form.Instance.Controls.Add(asd);
    }
    

提交回复
热议问题