使用属性在两个表单之间传递数据

时间:2011-02-23 07:04:59

标签: c# winforms

我在C#中的两个窗体之间传递数据。 Form1是主窗体,其文本框将接收从form2_textbox&传递给它的文本。将其显示在其文本框(form1_textbox)中。

首先,打开form1,使用空文本框和按钮,在单击form1_button时,将打开form2。在Form2中,我在form2_textbox&中输入了一个文本。然后点击按钮(form2_button).ON点击此按钮的事件,它会将文本发送到form1的文本框& form1将以其空的form1_textbox与来自form2的文本聚焦。

我正在使用属性来实现此任务。 FORM2.CS

公共部分类Form2:表格 {     //在表单2中声明事件     公共事件EventHandler SomeTextInSomeFormChanged;

public Form2()
{
    InitializeComponent();

}
public string get_text_for_Form1
{
    get { return form2_textBox1.Text; }
}

//On the button click event of form2, the text from form2 will be send to form1:

public void button1_Click(object sender, EventArgs e)
{
    Form1 f1 = new Form1();
    f1.set_text_in_Form1 = get_text_for_Form1;

//if subscribers exists
if(SomeTextInSomeFormChanged != null)
{
    SomeTextInSomeFormChanged(this, null);
}

}

}

Form1.cs的

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public string set_text_in_Form1
    {
        set { form1_textBox1.Text = value; }
    }

    private void form1_button1_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.Show();
        f2.SomeTextInSomeFormChanged +=new EventHandler(f2_SomeTextInSomeFormChanged);  
    }

    //in form 1 subcribe to event
    Form2 form2 = new Form2();

    public void f2_SomeTextInSomeFormChanged(object sender, EventArgs e)
    {
        this.Focus();

    }
}

3 个答案:

答案 0 :(得分:3)

在form2中,您需要创建事件并在form1中订阅它。多数民众赞成。

//declare event in form 2
public event EventHandler SomeTextInSomeFormChanged;

// call event in form2 text_changed event
if(SomeTextInSomeFormChanged != null)
   SomeTextInSomeFormChanged(this, null);

//in form 1 subcribe to event
var form2 = new Form2();
form2.SomeTextInSomeFormChanged += SomeHandlerInForm1WhereYouCanSetForcusInForm1

<强>更新

窗体2:

public Form2()
{
    InitializeComponent();
}

public void button1_Click(object sender, EventArgs e)
{
//if subscribers exists
  if(SomeTextInSomeFormChanged != null)
  {
    SomeTextInSomeFormChanged(form2_textBox1, null);
  }
}

Form1中:

public partial class Form1 : Form { 

   public Form1() { InitializeComponent(); }

    private void form1_button1_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.Show();
        f2.SomeTextInSomeFormChanged +=new EventHandler(f2_SomeTextInSomeFormChanged);  
    }

    public void f2_SomeTextInSomeFormChanged(object sender, EventArgs e)
    {
        var textBoxFromForm2 = (TextBox)sender;
        form1_textBox1.Text =  textBoxFromForm2.Text
        this.Focus();
    }
}

答案 1 :(得分:2)

下面列出的网站有很好的教程。这个特定的页面演示了如何实现这一目标:

http://www.vcskicks.com/data-between-forms.php

答案 2 :(得分:0)

这是怎么回事。

((Form2)Application.OpenForms["Form2"]).textBox1.Text = "My Message";