2014-01-20 42 views
-7

我有一个包含两种形式的项目。我必须将textbox1中的数据form2传递给form1中定义的变量字符串m。我的代码写在下面,但变量字符串m是恒定的。两种形式之间传递的数据

表2:

public partial class Form2 : Form 
{ 
    Form1 frm1; 
    public Form2() 
    { 
     InitializeComponent(); 
     frm1 = new Form1(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     frm1.ModifyTextBoxValue = textBox1.Text; 
     this.Close(); 
    } 

表1:

public partial class Form1 : Form 
{ 
    string m = "12"; 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    public string ModifyTextBoxValue 
    { 
     get { return textBox1.Text; } 
     set { m = value; } 
    } 
} 
+4

那么问题是什么? – andy

回答

0

你可以通过Form1的引用到窗体2 - 在Form1中揭露,你希望他们之间的共享性。

0

为了保持这个简单的我会尝试这个例子:

窗体2类

private string welcomeToStackOverflow; 

private void button1_Click(object sender, EventArgs e) 
{ 

    textBox1.Text = welcomeToStackOverflow; 
    Form1 frm = new Form1(welcomeToStackOverflow); 

} 

Form1类

private string welcome; 
public Form1(string wel) 
{ 
    this.welcome = wel; 
    InitializeComponent(); 
} 
0

修改您form2代码,并获得form1参考(如Yanshof说):

public partial class Form2 : Form 
{ 
    Form1 frm1; 
    public Form2(Form refForm1) 
    { 
     InitializeComponent(); 
     //frm1 = new Form1(); //remove this line 
     frm1 = refForm1; //assign reference of "form1" to "frm1" 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     frm1.ModifyTextBoxValue = textBox1.Text; 
     this.Close(); 
    } 

现在您还需要传递参考。当您拨打form2时,请拨打电话:

Form2 frm2 = new Form2(this); //here "this" is the reference of "Form1"