Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass string value from one form to another form's load event in C #

Tags:

c#

winforms

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";
}
like image 985
AbdelMalek Avatar asked Jun 06 '11 23:06

AbdelMalek


4 Answers

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();
}
like image 51
rsbarro Avatar answered Nov 14 '22 03:11

rsbarro


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();


}
like image 5
rerun Avatar answered Nov 14 '22 02:11

rerun


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.

like image 1
slugster Avatar answered Nov 14 '22 03:11

slugster


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 .... 
like image 1
Mani Avatar answered Nov 14 '22 03:11

Mani