I need to pass a string value from Form1
:
public void button1_Click(object sender, EventArgs e)
{
string DepartmentName = "IT";
Form2 frm2 = new Form2();
Frm2.Show();
this.Hide();
}
into the Form2
Load
event. For example:
private void Form2_Load(object sender, EventArgs e)
{
MessageBox.Show(DepartmentName);
// or
// string sql1 = "select Service_Name from Service, " +
// "EmployeeService where E_Dep = '" + DepartmentName + "' " +
// "and s_ID = Service_ID";
}
Just create a property on the Form2 class and set it before you show Form2.
public class Form2
{
...
public string MyProperty { get; set; }
private void Form2_Load(object sender, EventArgs e)
{
MessageBox.Show(this.MyProperty);
}
}
From Form1:
public void button1_Click(object sender, EventArgs e)
{
string departmentName = "IT";
Form2 frm2 = new Form2();
frm2.MyProperty = departmentName;
frm2.Show();
this.Hide();
}
Remember that forms are just classes like any other
public class Form2 : form
{
public string ShowMe {get;set;}
private void Form2_Load(object sender, EventArgs e)
{
MessageBox.Show(ShowMe);
}
}
From Form 1
public void button1_Click(object sender, EventArgs e)
{
string DepartmentName = "IT";
Form2 frm2 = new Form2();
frm2.ShowMe = DepartmentName ;
Frm2.Show();
this.Hide();
}
You don't do it that way. Instead you can pass your string value on the constructor:
public class Form2
{
public Form2(string myParameter) : this()
{
//do whatever you need to do with myParameter
}
}
the other answerers have also told you how to do it with a public property.
There is an easier way to pass the string from Form2 to Form1. Create a relationship between the forms and in Form2, create a variable of Form1, invoke the variable in Form1 and assign the value to it ....
public partial class Form_2 : Form
{
public readonly Form1 _form1;
public Form_2(Form1 form1)
{
_form1 = form1;
InitializeComponent();
}
private void Form2(object sender, EventArgs e)
{
_form1.Remark = txtbx_remark.Text;
}// Remark is a string in Form1 ....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With