I'm doing some validations in C# with ErrorProvider.
The validations are about TextBox
.
//Llama al método valida para decidir si el TextBox está vacío.
private void textBox1_Validating(object sender, CancelEventArgs e)
{
valida(sender, e, textBox1, errorProvider1);
}
//Método que recibe un textbox y un Error provider para validar si el textBox esta vacio.
private void valida(object sender, CancelEventArgs e, TextBox tb, ErrorProvider error)
{
if (string.IsNullOrEmpty(tb.Text))
{
e.Cancel = true;
error.SetError(tb, "Campos Vacios");
}
}
//valida cuando el TextBox pierde el foco y quita el ErrorProvider si no está vacío
private void textBox1_Validated(object sender, EventArgs e)
{
errorProvider1.SetError(textBox1, "");
}
//Cerrar ventana
private void btnCerrar(object sender, EventArgs e)
{
this.Close();
}
I have the problem when ErrorProvider
it is activated so to speak. If the TextBox
one I am validating is empty it shows the ErrorProvider
, and the cursor stays in that TextBox
empty waiting to be validated again.
But:
Why can't I close the window when it
ErrorProvider
's active?Why can't I Tab or change the cursor while it
ErrorProvider
's active?
It is a desktop application made in C#.
When the form has that error sign I can't change the cursor, much less close the window.
EDIT:
If I remove the e.cancel = true;
it does not show me the ErrorProvider
EDIT2
In the event Form1_FormClosing
of the form I did what @JLPrieto told me e.cancel = false;
which works only when the X of the form is pressed and the form closes. But if I do it from button1 this.close()
it doesn't close the window when I press the button.
Well, the problem here is that when the property is set to
Cancel
, it will always block any event that occurs after the event .CancelEventArgs
true
Validating
In this case, the conflicting events are
Form.FormClosing
,Button.Click
andKeyPress
that prevents the next control from being selected withTab
, since I was testing your code and indeed, the eventClick
of your cancel button is never executed (I tried with a MessageBox), neither is the eventFormClosing
.The solution?
Using Property Control.CausesValidation , is a boolean that gets or sets a value indicating whether the control causes validation to be performed on all controls that require validation when they receive focus.
So in your case it would be like this:
And it is that if the property
CausesValidation
is set tofalse
, the eventsValidating
andValidated
are suppressed.Well, I have developed a block of code that may be useful to you, remove the events
Validating
andValidated
and put this in yourForm_Load
:Yes,
GotFocus
and eventsLostFocus
are deprecated, but there are still cases where they can be used; if what you want is something modern, then you need the eventsEnter
andLeave