Respected Users, i am trying to pass a value one Form2 to Form1, first of all in Form1 upon TextBox if i press Escape key then it will move me to Form2, now i want when i enter Value in Form2 TextBox and press the button then control move to back to Form1 and close the Form2 and show the value of Form2.TextBox into Form1.TextBox further i will show this value in MessageBox in Form1 by pressing Button, kindly guide me in easiest way i will be very thank full.
here is the code which i was using
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace twoFormsDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
Form2 form2 = new Form2();
form2.ShowDialog();
this.Close();
}
}
private void Form1_Load(object sender, EventArgs e)
{
Form1 form1 = new Form1();
textBox1.Text = Form2.SetValueForText;
form1.Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(textBox1.Text);
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace twoFormsDemo
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public static string SetValueForText = "";
private void button1_Click(object sender, EventArgs e)
{
SetValueForText = textBox1.Text;
Form2 form2 = new Form2();
form2.SendToBack();
this.Close();
}
}
}
You have two options for that:
I recommend the second way if you're not trying to access this value anywhere else.
Create an event with custom EventArgs that allow you to store a string inside them in your Form2 and make sure to raise it whenever you need to. You can subscribe this event in Form1 at the point you create the instance of Form2. Then you can work with the string value in your event handler.