C# 是否将数据从表格2(文本框2)传输到表格1(文本框1)?
可能重复:C# 是否将数据从表格2(文本框2)传输到表格1(文本框1)?,c#,winforms,C#,Winforms,可能重复: 我是C的新手,在谷歌上找不到我想要的答案,所以我希望这里有人能帮我。我只是在练习将数据从一个表单传输到另一个表单(或者传递,不管你怎么称呼它) 以下是我所拥有的: 我有两张表格-Form1和Form2 Form1包含一个文本框(名为txtForm1)和一个按钮(名为btnForm1)。 Form2包含一个文本框(名为txtForm2)和一个按钮(名为btnForm2) 运行应用程序后,通过单击按钮btnForm1,用户将打开Form2。用户在文本框(txtForm2)中写入的文本应
我是
C
的新手,在谷歌上找不到我想要的答案,所以我希望这里有人能帮我。我只是在练习将数据从一个表单传输到另一个表单(或者传递,不管你怎么称呼它)
以下是我所拥有的:
我有两张表格-Form1
和Form2
Form1
包含一个文本框(名为txtForm1
)和一个按钮(名为btnForm1
)。Form2
包含一个文本框(名为txtForm2
)和一个按钮(名为btnForm2
)
运行应用程序后,通过单击按钮btnForm1
,用户将打开Form2
。用户在文本框(txtForm2
)中写入的文本应传输到Form1
中的文本框(txtForm1
,哪个按钮被禁用)
我怎样才能转车
编辑:好的,我需要澄清的是,这是我所有的代码: Form1(打开Form2的按钮): Form2(关闭Form2的按钮):
我没有别的了。(我完全是新手)创建一个公共变量,将文本框中的值传递给它,然后传递到第二个表单
public static string myVar;
myVar = txtForm2.Text;
当你回到第一种形式时:
txtForm1.Text=Form2.myVar代码>在您的表格2中,您应该有如下内容:
private void btnForm2_Click(object sender, EventArgs e)
{
this.Hide();
}
public String GettxtForm2()
{
return txtForm2.Text;
}
现在,在form1中,您可以通过以下方式访问txtForm2:
Form2 form2 = new Form2();
//on click btnForm1 show that form2 where you can edit the txtForm2
private void btnForm1_Click(object sender, EventArgs e)
{
form2.Show();
}
//after you save the txtForm2 when you will focus back to form1 the txtForm1 will get the value from txtForm2
private void Form1_Enter(object sender, EventArgs e)
{
txtForm1.Text = Form2.GettxtForm2();
}
您可以轻松地修改所有这些逻辑发生的事件…在表单1
中:
public void SetTextboxText(String text)
{
txtForm1.Text = text;
}
private void btnForm1_Click(object sender, EventArgs e)
{
var frm = new Form2(this); // pass parent form (this) in constructor
frm.Show();
}
在表格2中
:
Form _parentForm;
public Form2(Form form)
{
_parentForm = form;
}
private void txtForm2_TextChanged(object sender, EventArgs e)
{
_parentForm.SetTextboxText(txtForm2.Text); // change Form1.txtForm1.Text
}
试试这个;)
表格1:
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;
}
它是WinForms还是WPF应用程序?@Rotem我这样做只是为了方便访问。我应该不这样做吗?将其公开
shout可以让它在任何地方都可以访问,只要您有实例的引用。使其static
意味着该值将在所有Form2
实例之间共享。使静态允许我通过Form2访问它。
表示法,还是我错了?我发现它更容易记住。它允许您通过类名(可能是Form2
)而不是实例来访问它。不过,你应该意识到它的其他含义。在您的特定情况下,这可能很好,但这不是很好的做法,除非Form2
是单例。谢谢。我会记下=)
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2(textBox1.Text);
frm2.Show();
this.Hide();
}
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;
}