尊敬的用户, 我试图将一个Form2传递给Form1,首先在TextBox上的Form1上,如果我按Escape键然后它会将我移动到Form2,现在我想要当我在Form2 TextBox中输入Value并按下按钮然后控制移动到回到Form1并关闭Form2并将Form2.TextBox的值显示到Form1.TextBox中,我将通过按Button在Form1中的MessageBox中显示此值,请以最简单的方式指导我,我将非常感谢。
这是我正在使用的代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace twoFormsDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
Form2 form2 = new Form2();
form2.ShowDialog();
this.Close();
}
}
private void Form1_Load(object sender, EventArgs e)
{
Form1 form1 = new Form1();
textBox1.Text = Form2.SetValueForText;
form1.Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(textBox1.Text);
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace twoFormsDemo
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public static string SetValueForText = "";
private void button1_Click(object sender, EventArgs e)
{
SetValueForText = textBox1.Text;
Form2 form2 = new Form2();
form2.SendToBack();
this.Close();
}
}
}
答案 0 :(得分:1)
您有两种选择:
如果您不想在其他地方尝试访问此值,我建议采用第二种方式。
使用自定义EventArgs创建一个事件,允许您在 Form2 中将字符串存储在其中,并确保在需要时提升它。您可以在创建 Form2 实例时在 Form1 中订阅此活动。然后,您可以在事件处理程序中使用字符串值。
答案 1 :(得分:1)
你离这儿不远......
通过设置CyclicBarrier barrier = new CyclicBarrier(3);
Runnable thread = new Runnable()
{
@Override
public void run()
{
try
{
barrier.await();
for (int i = 0; i < 10; i++)
{
System.out.printf("%d%n", i);
}
}
catch (InterruptedException | BrokenBarrierException ex)
{
ex.printStackTrace();
// handle the exception properly in real code.
}
}
};
更改Form2。这将解除它并在DialogResult
点将执行返回到Form1。您的字段不需要ShowDialog
,但是:
static
现在在Form1中,使用Form2的实例来获取&#34; OK&#34;被送回:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string SetValueForText = "";
private void button1_Click(object sender, EventArgs e)
{
SetValueForText = textBox1.Text;
this.DialogResult = DialogResult.OK;
}
}
*在public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
Form2 form2 = new Form2();
if (form2.ShowDialog() == DialogResult.OK)
{
textBox1.Text = form2.SetValueForText;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(textBox1.Text);
}
}
活动中删除该代码!
答案 2 :(得分:-3)
您需要将Form视为一个愚蠢的UI层。应该有较低层来创建这些表单并与它们一起使用。查看表单实例的创建位置(获取灵感)。查看MVC和MVVM模式以获取更多信息。