需要帮助让系统从Form2 C#中读取字段

时间:2013-09-21 15:08:12

标签: c# winforms forms

我正在创建一个小程序,可以说话,可以为我做一些小任务。我想创建第二个表单(Form2),我将在其中输入我的姓名和其他个人信息。

如何让Form1读取Form2中的文本字段?

4 个答案:

答案 0 :(得分:3)

  

如何让Form1读取Form2中的文本字段?

大概Form1创建Form2的实例...所以请坚持该实例,并在表单上公开适当的属性:

Form2 form2 = new Form2();
form2.Show(); // Or ShowDialog?

string name = form2.UserName;

UserName的实现可能只是从文本字段中获取值:

public string UserName { get { return userNameTextField.Text; } }

可以直接用属性公开文本字段,但我个人认为表单应该“拥有”它的UI,而不是让其他代码搞乱它。

答案 1 :(得分:0)

您可以创建方法和form1以从textfields

中检索数据
public string GetTextFieldText()
{
     return textfield.Text;
}

或者用属性

包装它
public string TextField
{
    get
    {
        return textfield.Text;
    }
}

然后从form2访问它,如下所示:

Form1 frm1 = new Form1();
string text = frm1.TextField; // Or GetTextFieldText()

答案 2 :(得分:0)

使用修饰符public创建全局变量,然后使用Text_Changed事件或button_click事件将文本框的文本分配给变量(如果要在按钮单击后检索文本)。

然后在Form1。你用

    Form2 form = new Form2();
    //Then do whatever u want with the variable
    MessageBox.Show(form.globalVariableName);

将文本框的修饰符属性设置为publicform2

中的Form1
    Form2 form = new Form2();
    //Then do whatever u want with the textbox
    MessageBox.Show(form.TextBoxName.Text);

答案 3 :(得分:0)

这应该让你开始:

//Global Variable
Form2 frm2;

//assuming form1 is the creator of form2
public Form1()
{
   frm2 = new Form2();
}

//in your Form1, under read data button for example:
string myName = frm2.TextBox1.Text;