![](/img/trans.png)
[英]Passing values from form to function in other class then call function in form
[英]Passing Values from One Form to an Other Form as Consutrutor Parameters
有两种形式form1和form2。 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();
}
}
使用您的问题代码,我试图解决我们的问题:)
// 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.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.