[英]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.