locked
How to pass string value from one form to another form’s load event using C#

    Question

  •  For example

    I need to pass string value from form 1

     

      public void button1_Click(object sender, EventArgs e)

            {

               string DepartmentName = "IT";

                Form2 frm2 = new Form2();

                Frm2.Show();

                this.Hide();

            }

    to form 2 load event

    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";

          

            }


    Monday, June 06, 2011 11:18 PM

Answers

  • You can add this to Form2's constructor:

    public partial class Form2 : Form
    {
      // Change the constructor:
      public Form2(string departmentName)
      {
        InitializeComponent();
    
        this.DepartmentName = departmentName;
      }
    
      // Add a property where it can be stored:
      public string DepartmentName { get; set; }
    
      // This will work now
      private void Form2_Load(object sender, EventArgs e)
      {
          MessageBox.Show(DepartmentName);   
      }
    }
    

    Once you've done that, all you need to do is change your form1's button click to:

    public void button1_Click(object sender, EventArgs e)
    {
          string DepartmentName = "IT";
          Form2 frm2 = new Form2(DepartmentName); // Pass this in here!
          Frm2.Show();
          this.Hide();
    }
    


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Monday, June 06, 2011 11:25 PM

All replies

  • You can add this to Form2's constructor:

    public partial class Form2 : Form
    {
      // Change the constructor:
      public Form2(string departmentName)
      {
        InitializeComponent();
    
        this.DepartmentName = departmentName;
      }
    
      // Add a property where it can be stored:
      public string DepartmentName { get; set; }
    
      // This will work now
      private void Form2_Load(object sender, EventArgs e)
      {
          MessageBox.Show(DepartmentName);   
      }
    }
    

    Once you've done that, all you need to do is change your form1's button click to:

    public void button1_Click(object sender, EventArgs e)
    {
          string DepartmentName = "IT";
          Form2 frm2 = new Form2(DepartmentName); // Pass this in here!
          Frm2.Show();
          this.Hide();
    }
    


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Monday, June 06, 2011 11:25 PM
  • Thank you it’s work as I need

    Monday, June 06, 2011 11:36 PM