开发者

How can I fire an event so my other form reacts to it?

I have this form called MainForm.cs. When I click Enter The Progam button I display another form using the .ShowDialog() method.

In this new form called LoginBox.cs, I check if the entered credentials are valid and if they are I want my MainForm.cs to react with either a positive responde (the actual software form opens) or negative response a MessageBox alerting him of the failure.

It's a very simple use case, but I don't know how to solve this correctly and efficiently. Thank you.

private void button1_Click(object sender, EventArgs e)
        {
            LoginBox login = new LoginBox();
            login.ShowDialog();
        }

//And in the LoginBox.cs file:
private void button1_Click(object sender, EventArgs e)
     开发者_开发问答   {
            if ((txtUser.Text == "admin") && (txtPassword.Text == "123"))
            {

            }
        }


If you open the form with ShowDialog it returns a DialogResult which you can check in your main form.

LoginBox login = new LoginBox();
DialogResult dialogResult = login.ShowDialog();
if (dialogResult == DialogResult.OK)
{
     // etc...
}

You can set the value of DialogResult in your LoginBox form:

DialogResult = DialogResult.OK;


Others have mentioned using DialogResult, which can work--but might be abused a bit in this use-case. Its intended purpose is to let the parent form know what the user did on a child form--did they click OK or Cancel? Did they click Retry or Abort? It's not intuitive that it should be used for authentication purposes.

So--what's better? Probably a combination...

Your LoginBox class is a Dialog, so returning a DialogResult should be expected--but should also only be used to indicate what the user did on the Form, not the outcome of the authentication.

I would suggest looking into the usage of some other dialogs, such as OpenFileDialog. It returns a DialogResult to specify whether to go ahead with the file opening, but it doesn't actually open the file until being explicitly told to do so. This means the consuming code has to both check the result and instruct the dialog to perform it's function, so it's not perfectly simple--but it's fairly conventional.

Here's an example of how I would suggest you use LoginBox:

private void button1_Click(object sender, EventArgs e)
{
    LoginBox login = new LoginBox();
    if (login.ShowDialog() == DialogResult.OK) // Let the user input their credentials and click OK or Cancel
    {
        if (!login.ValidateCredentials) // Perform the authentication with the collected credentials
        {
            MessageBox.Show("The specified Credentials were invalid!");
        }
    }
}


Add an Event to the LoginBox. Then have the MainForm handle that event. In the event handler proceed with the additional logic that you want to perform.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜