C# WinForm Validate Checkbox and Error if at least

2019-08-09 05:09发布

I seem to have a problem with validating my user control.

Help would be awesome :)

If I have at least one check box checked, I will process through a loop all checkboxes.

If I have no checkboxes checked, the form generates an error.

An if with just one checkbox before the foreach would be an easier solution for me but I have quite a lot of checkboxes on this user control and dont want to list them all....

Also I think there is some logic problem, cos even select a checkbox I still get my warning messagebox... and I the warning messagebox loops causing it never to close...

  private void ValidateButton_Click(object sender, EventArgs e)
        {

            foreach (var control in this.Controls)
            {
                if (control is CheckBox)
                {
                    if (((CheckBox)control).Checked)
                    {
                           //CODE GOES HERE to
                           //Process checked in background
                           //and then
                           validatebutton.hide();
                           nextbutton.show();
                    }  
                }
                else
                {
                    DialogResult uncheckederror = MessageBox.Show("You must select at least one checkbox",
                        "Validation Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                }
            }

}

1条回答
冷血范
2楼-- · 2019-08-09 05:45

Check the following:

private void ValidateButton_Click(object sender, EventArgs e)
    {

        Boolean checkboxFlag = false;
        foreach (var control in this.Controls)
        {
            if (control is CheckBox)
            {
                if (((CheckBox) control).Checked)
                {
                    checkboxFlag = true;
                    validatebutton.hide();
                    nextbutton.show();

                }
            }

        }
    if(!checkboxFlag)
        {
            DialogResult uncheckederror = MessageBox.Show("You must select at least one checkbox",
                "Validation Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
                MessageBoxDefaultButton.Button1);
        }
    }
查看更多
登录 后发表回答