UserControl x Form - Cancel screen event after UC validation

2

I have a UserControl, which does a validation on the Validated event, and on the screen, I have the Confirm button.

When I use the ALT + C shortcut to run the button event, it will perform validated event validation, and then the button event.

How do I cancel the button event when my UserControl validation fails?

I do not know if it was very clear, what I'm trying to do. If it's a bit confusing, here are some "prints" for better understanding:

UserControl:

Sourcecodeinform:

When I click the Confirm button on the screen, it works fine.

  • Performs the Validated validation first, and returns. And it does not execute the message that is in the "Confirm" button

As I said above, if you run through the ALT + C shortcut, it will trigger both events.

Does anyone have a solution for this?

    
asked by anonymous 21.07.2015 / 22:35

1 answer

1

The Control.Validated event will only be called after losing focus.

Your code only works because you always return the focus to the control textbox after the validate event, however, by triggering ALT + C and taking the focus of the text (and doing the validation) it still executes the Confirm button code.

If, for example, you click on the form and click the confirm button, it will not validate, it will only execute the confirm button code.

Do as in the example below that will work.

Code in UseControl

public partial class MyTextBox: UserControl
{
    public MyTextBox()
    {
        InitializeComponent();
    }

    private void textBox1_Validated(object sender, EventArgs e)
    {

    }

    public void ValidaTexto()
    {
        if (textBox1.Text.Contains("a"))
        {
            MessageBox.Show("Erro de Validação - Não executar evento...");
        }
        else
            MessageBox.Show("Validação OK!");
    }
}

Call on Form

    public Form1()
    {
        InitializeComponent();
    }

    private void btnConfirmar_Click(object sender, EventArgs e)
    {
        MyTextBox.ValidaTexto();
    }
    
30.05.2016 / 18:00