Usercontrol x Form - Cancel screen event after UC validation

Asked

Viewed 375 times

2

I have a Usercontrol, which does a validation in 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 run the Validated event validation, and after that the button event.

There’s a way I can "cancel" the button event when there’s an error in my validation in Usercontrol?

I do not know if it was very clear, what I am trying to do. If you are a bit confused, follow below "prints" for better understanding:

Usercontrol:

UserControl

Source code in the form:

Form

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

  • First executes Validated validation, and returns. And does not execute the message that is on the "Confirm"

As mentioned above, if you run by the ALT+C shortcut, it will trigger both events.

Does anyone have a solution to this?

  • How you are associating the ALT+C shortcut to the button event?

  • Marcus, good morning to you! .

  • Hello, please don’t post a print of your code in the question, put it yourself (like: start each line of code with four spaces at the beginning)

1 answer

1

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

Your code only works because you always focus back on control textbox after the event of validating, however, when activating the ALT+C in addition to taking the focus of the text (and doing the validation) it still executes the code of the button confirm.

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

Do as in the example below that will work.

Code in the 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 the Form

    public Form1()
    {
        InitializeComponent();
    }

    private void btnConfirmar_Click(object sender, EventArgs e)
    {
        MyTextBox.ValidaTexto();
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.