【问题标题】:Transfering data from Form2 (textbox2) to Form1 (textbox1)? [duplicate]将数据从 Form2 (textbox2) 传输到 Form1 (textbox1)? [复制]
【发布时间】:2013-01-08 12:02:16
【问题描述】:

可能重复:
Transfering data from Form2 (textbox2) to Form1 (textbox1)?

我是C# 的新手,我在 google 中找不到我正在寻找的答案,所以我希望这里有人可以帮助我。我只是在练习将数据(或传递,随心所欲地调用它)从一个表单传输到另一个表单。

这就是我所拥有的:

我有 2 个表单 - Form1Form2
Form1 包含一个文本框(名为 txtForm1)和一个按钮(名为 btnForm1)。
Form2 包含一个文本框(名为txtForm2)和一个按钮(名为btnForm2)。

运行应用程序后,通过单击按钮btnForm1,用户打开Form2。用户在文本框 (txtForm2) 中写入的文本应传输到 Form1 中的文本框 (txtForm1),该按钮被禁用。

我怎样才能进行这种转移?请帮忙。

好的,我需要清楚这是我拥有的所有代码:

Form1(打开按钮Form2):

    private void btnForm1_Click(object sender, EventArgs e)
    {
        new Form2().Show();
    }

Form2(关闭按钮Form2):

    private void btnForm2_Click(object sender, EventArgs e)
    {
        this.Close();
    }

我没有别的了。 (我是个新手)

【问题讨论】:

  • 您的第一个帖子已经收到 3 或 4 个答案。

标签: c#


【解决方案1】:

在 Form1 上:

private void button1_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2(textBox1.Text);
    frm2.Show();
    this.Hide();
}

在表格 2 上:

public partial class Form2 : Form
{
public string textBoxValue;
public Form2()
{
    InitializeComponent();
}

public Form2(string textBoxValue)
{
    InitializeComponent();
    this.textBoxValue = textBoxValue;
}

private void Form2_Load(object sender, EventArgs e)
{
    textBox2.Text = textBoxValue;
}

【讨论】:

  • 为什么需要公共字符串 textBoxValue ?
  • 我猜你不必公开
  • 我会说你根本不需要这个变量
  • @VladL 如果我删除变量,代码将不起作用。也许您可以提供一些示例代码?那我可以学习更好的方法吗?
  • 看我的回答。这是正确的 OOP 实现
【解决方案2】:

在 Form1 上:

private void btnForm1_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2(txtForm1.Text);
    frm2.ShowDialog();
    txtForm1.Text = frm2.GetText;
}

在表格 2 上:

public partial class Form2 : Form
{
  public string GetText { get {return txtForm2.Text;} }
  public Form2()
  {
    InitializeComponent();
  }

  public Form2(string textBoxValue)
  {
    InitializeComponent();
    this.txtForm2.Text = textBoxValue;
  }

private void btnForm2_Click(object sender, EventArgs e)
    {
        DialogResult = DialogResult.OK;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    相关资源
    最近更新 更多