Search code examples
c#textboxtransfer

Can't transfer tbox from 1 form to another tbox in another form c#


I have 2 forms, Form1 is the parent and ALog is the child. My goal is to have a textbox's text from Form1 (form1textbox) contents transfer over to a textbox on ALog (alogcheckbox)

This has to be done on the formload event on Alog and when the form shows from a button click on Form1

This is what I have currently:

Form1:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public string LabelText
    {
        get { return form1textbox.Text; }
        set { form1textbox.Text = value; }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ALog alogform = new ALog();

        alogform.Show();

    }
}

ALog:

 public partial class ALog : Form
{
    public ALog()
    {
        InitializeComponent();
    }

    public Form Alog;

    private void button1_Click(object sender, EventArgs e)
    {

    }

    private void ALog_Load(object sender, EventArgs e)
    {
        this.Form1.LabelText = textBox1.Text;
    }
}

I've seen other questions similar to mine and answers as well, but I can't seem to manage to get this to work.

Any help is appreciated, thanks.


Solution

  • You want to add a constructor to ALog that takes the value, and initialize it that way.

    ALog becomes:

    public partial class ALog : Form
    {
        public ALog(string value)
        {
            InitializeComponent();
    
            this.alogcheckbox.Text = value;
        }
    
        public Form Alog;
    
        private void button1_Click(object sender, EventArgs e)
        {
    
        }
    }
    

    And from Form1:

    private void button1_Click(object sender, EventArgs e)
    {
        ALog alogform = new ALog(form1textbox.Text);
    
        alogform.Show();
    }