简体   繁体   English

将值从一种形式传递到另一种形式作为消费者参数

[英]Passing Values from One Form to an Other Form as Consutrutor Parameters

There are two forms form1 and form2. 有两种形式form1和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. form12按钮单击需要在form2上传递一些值作为form2,s的构造函数参数,而在form1按钮单击时,form2需要显示和使用这些值。

//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 // 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. 一个简单的解决方案是在Form2上创建一个方法,该方法可以初始化您需要的任何内容。

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 : 因此,您现在需要在按钮的Click事件处理程序中做的就是:

// 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.
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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