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

时间:2010-08-02 04:20:42

标签: c# .net winforms

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

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

  

当前上下文中不存在名称“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。

任何帮助将不胜感激。

6 个答案:

答案 0 :(得分:3)

form2创建一个接受字符串的构造函数,并将新的form2传递form1.frm1Textbox.text传递给构造函数,然后将其设置为form2.frm2Textbox.text

Form2 form = new Form2(frm1Textbox.text);

在form2构造函数

public class Form2 : Form
{
    public Form2(string text)
    {
        frm2Textbox.Text = text; 
    }
}

答案 1 :(得分:1)

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
    }
}

答案 2 :(得分:0)

要从Form1实例化Form2class 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");

答案 3 :(得分:0)

在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();

答案 4 :(得分:0)

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

答案 5 :(得分:0)

在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;
 }
}
相关问题