0

我有一个 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();
}

我怎样才能做到这一点?谢谢!

4

2 回答 2

0

在 for 类中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!
    }
}
于 2013-06-18T11:13:03.690 回答
0

通常,它使用数据传输对象:

http://msdn.microsoft.com/en-us/library/ff649585.aspx

或域对象。

http://msdn.microsoft.com/en-us/magazine/dd419654.aspx

于 2013-06-18T10:02:12.787 回答