如何从 form1 到 form2 并取回值?
How to take value from form1 to form2 AND back?
好的,情况是这样的:
我想将 form1 中的字符串值取到 form2 中的文本框,对其进行编辑并将其发回并再次将其另存为 form1 中的字符串。就这么简单,但我太笨了,没能成功。是的,我用谷歌搜索并尝试了很长时间,但我似乎没有找到合适的标签。
我尝试了以下方法:
public partial class form1: Form
{
public form1()
{
InitializeComponent();
}
Project.form2 newform2 = new Project.form2();
string oldtext = "Text here";
void somefunction()
{
oldtext = newform2.getUpdateTxt();
}
}
和
public partial class form2: Form
{
Project.form1 newform1 = new Project.form1();
string UpdateTxt = "";
public form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
UpdateTxt = textBox1.Text;
this.Hide();
}
public string getUpdateTxt()
{
return UpdateTxt;
}
private void form2_VisibleChanged(object sender, EventArgs e)
{
textbox1.Text = newform1.oldtext.Text;
}
}
显然不起作用。因为它创建了一个无限循环。我也试过把
Project.form newform = new Project.form();
在自己的函数中。解决了循环,但现在它在初始化时重置了值。还尝试以某种方式像此处描述的那样为表单添加父级,但它没有帮助。
C# - How to make two forms reference each other
我能想到的最简单的解决方案是将要跨表单共享的值放在静态 属性 的静态 class:
中
public static class SharedVariables
{
public static string OldText { get; set; }
}
然后您可以将 TextBox.Text
设置为 属性 的值:
textBox1.Text = SharedVariables.OldText;
并且您可以分配在另一个 TextBox.Text
中输入的新值:
SharedVariables.OldText = textBox2.Text;
也就是说,根据表格的用途,这可能不是最佳解决方案。
好的,情况是这样的: 我想将 form1 中的字符串值取到 form2 中的文本框,对其进行编辑并将其发回并再次将其另存为 form1 中的字符串。就这么简单,但我太笨了,没能成功。是的,我用谷歌搜索并尝试了很长时间,但我似乎没有找到合适的标签。 我尝试了以下方法:
public partial class form1: Form
{
public form1()
{
InitializeComponent();
}
Project.form2 newform2 = new Project.form2();
string oldtext = "Text here";
void somefunction()
{
oldtext = newform2.getUpdateTxt();
}
}
和
public partial class form2: Form
{
Project.form1 newform1 = new Project.form1();
string UpdateTxt = "";
public form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
UpdateTxt = textBox1.Text;
this.Hide();
}
public string getUpdateTxt()
{
return UpdateTxt;
}
private void form2_VisibleChanged(object sender, EventArgs e)
{
textbox1.Text = newform1.oldtext.Text;
}
}
显然不起作用。因为它创建了一个无限循环。我也试过把
Project.form newform = new Project.form();
在自己的函数中。解决了循环,但现在它在初始化时重置了值。还尝试以某种方式像此处描述的那样为表单添加父级,但它没有帮助。 C# - How to make two forms reference each other
我能想到的最简单的解决方案是将要跨表单共享的值放在静态 属性 的静态 class:
中public static class SharedVariables
{
public static string OldText { get; set; }
}
然后您可以将 TextBox.Text
设置为 属性 的值:
textBox1.Text = SharedVariables.OldText;
并且您可以分配在另一个 TextBox.Text
中输入的新值:
SharedVariables.OldText = textBox2.Text;
也就是说,根据表格的用途,这可能不是最佳解决方案。