How to pass string value from one form to another form's load event in C #
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 Ser开发者_JS百科vice_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 ....
PRO TIP
In the future, think about it in a more generic way: a Form is just a class, and the Load event is just a method.
If you were trying to pass a value between 2 objects that weren't Forms, you would have a public property in one class that other objects could access. This is at the heart of rsbarro's answer, and what I like to call "Forms are classes too" :)
精彩评论