Validating event not fired for child controls of picturebox

1.5k Views Asked by At

Yesterday I have implemented some validating events for controls in a groupbox located on a WinForm. I have set the AutoValidate property of the form to Disabled, I have set the CausesValidation property of the controls to true and implemented the Validating event of the controls. By calling the ValidateChildren() method of the form I force that validating events are executed. This was working all fine.

But after placing this groupbox on top of a picturebox and setting the picturebox as parent of the groupbox then validating events aren't executed anymore....

Below some demo code. Form is only containing a picturebox, groupbox, textbox and button.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void textBox1_Validating(object sender, CancelEventArgs e)
    {
        MessageBox.Show("Validating textbox");
        e.Cancel = true;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (ValidateChildren())
            MessageBox.Show("Validation not executed :-(");
        else
            MessageBox.Show("Validation executed :-)");
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        groupBox1.Parent = pictureBox1;
    }
}
1

There are 1 best solutions below

4
On

The ValidateChildren() method calls ValidateChildren(ValidationConstraints.Selectable) to get the job done. That's a problem for a PictureBox, it isn't selectable. So none of its children get validated either.

Calling it with ValidationConstraints.None doesn't work either, the ability to validate child controls is implemented by ContainerControl and PictureBox doesn't derive from it. So you can't call ValidateChildren on the PictureBox either. Enumerating the controls yourself and triggering the Validating event can't work either, the PerformControlValidation() method is internal.

You'll need to re-think the idea of trying to turn the PictureBox into a ContainerControl. Most any control can resemble a picturebox, if not through the BackgroundImage property then through the Paint event.