如何将文本框值从Form1复制到Form2?

我有Form1,它有一个文本框和一个按钮。 当用户单击Form1的按钮时, Form2打开时带有一个标签控件,该控件带有Form1本框的值。

我所做的是将Form1的文本框修饰符设置为Public ,但是当我在Form2调用Form1的文本框名称时,出现错误

当前上下文中不存在名称“txtbx1”

我想知道为什么因为我已经将txtbx1的修饰符设置为Public

快速注意:我试图将Form2中的Form1实例化为:

 Form1 f1 = new Form1(); 

然后打电话

 f1.txtbx1.text 

奇怪的是Form1无法实例化(不突出显示)。 另一方面,如果我做Form2 f2 = new Form2(); Form2突出显示!

这是我如何从Form1显示Form2:

  SetSalary salForm = new SetSalary(); salForm.ShowDialog(); 

请注意,SetSalary表示Form2。

任何帮助将不胜感激。

form2创建一个接受字符串的构造函数,并在调用new form2form1.frm1Textbox.text传递给contructor,然后将其设置为form2.frm2Textbox.text

 Form2 form = new Form2(frm1Textbox.text); 

在form2构造函数中

 public class Form2 : Form { public Form2(string text) { frm2Textbox.Text = text; } } 
 public partial class Form1 : Form { Form2 f = new Form2(); private void button1_Click(object sender, EventArgs e) { textBox1.Text = f.ans(); /*-- calling function ans() and textBox1.Text is inside form1--*/ } } 

在form2中创建一个公共函数ans()….

 public partial class Form2 : Form { public string ans() { string s = textBox1.Text;/*-- assigning value of texBox1.Text to local variable s and textBox1.Text is another text box which is inside form 2 --*/ return s; // returning s } } 

要从Form2实例化Form1 ,必须将class Form1声明为public class Form1 ,或者如果它们位于同一个程序集(项目)中,则必须至少声明为internal class Form1

f1.txtbx1.text将不起作用,因为c#区分大小写,并且该属性称为Text ,而不是text

或者,您可以在Form2声明一个带有参数的构造函数,这样您就不TextBox成员公开为public:

 public class Form2 : Form { public Form2(string text) { txtbx1.Text = text; //txtbx1 does not need to be public } } 

然后在Form1调用var f2 = new Form2("label text goes here");

在Form2上公开一个公共属性(或一组属性,如果你有一个值可以传入),然后填充文本框。 这隐藏了它的显示方式的实现细节,如果有的话,它也遵循内置表单类使用的标准。 例:

 public class SetSalary { public SetSalary() { } public string SalaryText { get { return txtbox1.Text; } set { txtbox1.Text = value; } } } 

然后,在启动SetSalary时,您执行以下操作:

 SetSalary form = new SetSalary(); form.SalaryText = srcTextBox.Text; form.ShowDialog(); 

好的方法是使用Model-View-Presenter模式。 如果你是初学者(我想你是)那么你应该通过本书学习基础知识。 这可以帮助您最大限度地减少错误和糟糕的工程,并最大限度地提高您的技能。

在Form1上

 public class Form1 : Form { public Form2() { InitializeComponent(); } public static string MyTextBoxValue; protected void button1_Click(object sender, EventArgs e) { MyTextBoxValue = TextBox1.Text; } } 

在Form2上

 public class Form2 : Form { public Form2() { InitializeComponent(); } private void Form2_Load(object sender, EventArgs e) { label1.Text=Form1.MyTextBoxValue; } }