开发者

Validation in modal form

开发者 https://www.devze.com 2023-03-03 21:06 出处:网络
I have a simple modal form in which I have to check user entered data. But after validation the form gets closed. It behaves like this because of not empty DialogResult property but I need this value

I have a simple modal form in which I have to check user entered data. But after validation the form gets closed. It behaves like this because of not empty DialogResult property but I need this value for other purposes (in a parent form) Any ideas?

A little code to开发者_高级运维 clear things up


//This method creates and calls a modal form. 
public static Definition edit(Definition w)
{
    EditForm ed = new EditForm();
    DialogResult dr = ed.ShowDialog();
    if (dr == DialogResult.OK)
    {
       //update some fields of passed object
    }
    //other code
}

private void btnSave_Click(object sender, EventArgs e)
{
       if (validateForm())
       {
           DialogResult = DialogResult.Yes;
           Close();
       }
}



I would do it this way:

private void btnSave_Click(object sender, EventArgs e)
{
       if (validateForm())
       {
           DialogResult = DialogResult.Yes;
           Close();
       }
       else
       {
           DialogResult = DialogResult.None;
       }
}

I.e. as you said, clear the DialogResult.


Add a FormClosing event handler and then if the validation fails set e.Cancel = true:

private void EditForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (this.DialogResult == DialogResult.OK)
    {
        e.Cancel = !ValidateInput();
    }
}

This will leave you sub form open and let the user correct the mistakes. You can check whether the "OK" or "Cancel"/Window Close button has been clicked by checking the DialogResult and only performing the validation if it's OK.

0

精彩评论

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