2013-04-09 28 views
1

我想从class1设置textbox.text,但是当我按下按钮时什么也没有发生。怎么了?如何回调参数?

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 
     Class1 c; 
     private void button1_Click(object sender, EventArgs e) 
     { 
      c = new Class1(); 
      c.x(); 
     } 
    } 
} 

而且从class1

namespace WindowsFormsApplication1 
{ 
    class Class1 
    { 
     public static Form1 f; 

     public void x() 
     { 
      f = new Form1(); 
      f.textBox1.Text = "hello"; 
     } 
    } 
} 

这个代码我已经改变textBox1修饰符公众。

回答

3

当你做f = new Form1()你创建一个新的表单。如果你已经有一个Form1的实例打开,那么这会给你Form1的两个实例。在其中一个方法上调用方法不会影响其他方法。您必须将表单的引用传递给您的实例Class1,并调用该引用的方法。

有不同的方法来做到这一点。之一可能是通过参考作为参数传递给x方法:

public void x(Form1 f) 
{ 
    f.textBox1.Text = "hello"; 
} 

当调用x你可以通过它的特殊变量this,其是该代码相关联的对象。这会将Form1的实例传递给x,以便x可以使用它。

c.x(this); 
+0

你能举个例子吗,我是新来的c# – 2013-04-09 09:17:44

+0

是的。我已经更新了答案。 – 2013-04-09 09:25:41

+0

Thnx Marcus @Marcus Karlsson – 2013-04-09 09:41:33

1
private void button1_Click(object sender, EventArgs e) 
{ 
    c = new Class1(this); 
    c.x(); 
} 


class Class1 
{ 
    public static Form1 f; 

    public Class1(Form1 form) 
    { 
     f = form; 
    } 

    public void x() 
    { 
     f.textBox1.Text = "hello"; 
    } 
} 

的问题是,你在x方法创建一个新的Form1的实例。根据我的代码改变你的代码,它会工作。

+0

Thanx @ laszlokiss88 – 2013-04-09 09:29:19