将数据从一种形式传输到另一种形式

时间:2013-06-18 09:57:45

标签: c# winforms data-transfer

我有一个带有两个表单的C#应用​​程序(form1,form2)。在btnTransfer_click上的form1中我打开第二个表单。

private void btnTransfer_Click(object sender, EventArgs e)
{
    Form2 frmConn = new Form2 ;
    frmConn .Show();

    //i need here values from second form 

}

在第二种形式中我有2个文本框(txtUser,txtPassword)和一个按钮(btnOk)。在按钮btnOk我验证用户和密码,如果是正确的我必须回到第一个表单并在点击按钮上获取此值。

在Form2中:

private void btnOk_Click(object sender, EventArgs e)
{
      //verify if txtUser and txtPassword are correct 
    //if are corrects i have to send back to first form
    this.Close();
}

我该怎么做? 谢谢!

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

form2的课程中,创建两个public类属性,一个用于每个文本框的值:

private String _username = null;
public String UserName { get { return _username; } }
private String _password = null;
public String Password { get { return _password; } }

form2中,您可以验证并分配给属性:

private void btnOk_Click(Object sender, EventArgs e)
{
    //verify if txtUser and txtPassword are correct

    if (correct)
    {
        _username = txtUser.Text;
        _password = txtPassword.Text;
    }
    this.Close();
}

然后您可以在form1代码中检索它们:

private void btnTransfer_Click(Object sender, EventArgs e)
{
    //This using statement will ensure that you still have an object reference when you return from form2...
    using (Form2 frmConn = new Form2())
    {
        frmConn.Show();

        String user = frmConn.UserName;
        String pass = frmConn.Password;

        if (!String.IsNullOrEmpty(user) && !String.IsNullOrEmpty(pass))
            //do something with them, they are valid!
    }
}