简体   繁体   中英

Transfer info of dateTimePicker and textbox from form1 to form2

okay so I'm trying to transfer my info of name(textbox) and birthdate(dateTimePicker) to Form2. So, basically i have a form1 with name,birthdate and btn1 and when I click btn1 I go to Form2. I have another button btn2 in form2. Question: So how can I display value of form1 textbox and datetimepicker when I click my btn2 in Form2.

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        this.Hide();
        f2.Show();

    }

    private void button2_Click_1(object sender, EventArgs e)
    {

    }

In the event where you want to move from form1 to form2

Form2 obj = new Form2(textbox1.Text,DateTime.Value);
this.Hide();
Form2.Show();

In form 2

public form2()
{
InitializeComponent();
//if you need something
}
string someName="";
DateTime dt;
public form2(string name,Datetime value)
{
InitializeComponent();
someName=name;
dt=value;
}

Now your someName will have that value

The quick way is to make sure that the controls on Form2 are public, then populate them like this...

Form2 f2 = new Form2();
f2.ControlName.Text = this.ControlName.Text;
f2.Show();

However I would encapsulate this into a public function.

Form2 f2 = new Form2();
f2.Populate(txtValue1.Text, dtDateTime.Value);
f2.Show();

and in Form2

public void Populate(string Value1, DateTime Value2)
{
   txtValue1.Text = Value1;
   dtValue2.Value = Value2;
}

Form1

        public Form1()
        {
            InitializeComponent();
            Load += delegate
            {
                var frm2 = new Form2 { DateValue = dateTimePicker1.Value.ToShortDateString() };
                frm2.Show();
            };
        }

Form2

        public string DateValue
        {
            get { return textBox1.Text; }
            set { textBox1.Text = value; }
        }

        public Form2()
        {
            InitializeComponent();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM