将值从一种形式传递到另一种形式,作为授权参数



有两个Form1和Form2。Form12按钮单击需要在Form2上以Form2,s约束参数以及Form1 Form1 Form2的按钮2所需显示和使用这些值的按钮。

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

使用您的问题代码我尝试解决我们的问题:)

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

简单的解决方案是在form2上制作一种方法,该方法可以执行您需要的任何内容。

例如:

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

因此,您现在需要在按钮的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");

这里的目的不是要使构造函数复杂化,因为单独的方法更容易维护,并且更容易遵循。

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

相关内容

最新更新