简体   繁体   中英

Passing Values from One Form to an Other Form as Consutrutor Parameters

There are two forms form1 and form2. form12 button clicks in need to pass some value on form2 as form2,s Construtor Parameters, and on button click of form1 form2 need to show and use those value.

//form1
{
    private void btn_Click(object sender, EventArgs e)
    {
     int a=1;
     int b=2;
     int c=3;
    }
}
//form2
{
 private int a=b=c=0; 
 public Frm2(/*pass parameters here*/)
        {
            InitializeComponent();
        } 
}

Using your code of problem i tried to solve our problem :)

//form1

 {
        private void btn_Click(object sender, EventArgs e)
        {
         int a=1;
         int b=2;
         int c=3;

         Form2 frm=new Form2(a,b,c);
         frm.show();
        }
    }
//form2


 {
     private int a=b=c=0; 

     //it will be main load of your form 
     public Frm2()
            {
                InitializeComponent();

            } 

     //pass values to constructor 
     public Frm2(int a, int b, int c)
            {
                InitializeComponent();
                this.a = a;
                this.b = b;
                this.c = c;
            } 
    }

The simple solution is to make a method on Form2 that would do the initialization of anything you require.

For example :

public class Form2
{

  public Form2()
  {
     InitializeComponent();
  }

  // Call this method to initialize your form
  public void LoadForm(int a, int b, int c)
  {
      // Set your variables here
  }

  // You can also have overloads to cater for different callers.
  public void LoadForm(string d)
  {
      // Set your variables here
  }

}

So all you would need to do now in your button's Click event handler is :

// Instantiate the form object
var form2 = new Form2();

// Load the form object with values
form2.LoadForm(1, 5, 9);

// Or 
form2.LoadForm("Foo Bar");

The point here is not to complicate the constructors since a separate method is easier to maintain and somewhat easier to follow.

public class Form2
{

    public Form2()
    {
        InitializeComponent();
    }

    //add your own constructor, which also calls the other, parameterless constructor.

    public Form2(int a, int b, int c):this()
    {
        // add your handling code for your parameters here.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM