I have many text boxes with which I do various validations and in one point I just need to delete an errorProvider if the code reaches that if statement. What I have done in this:
if (errorProviderSame1.DataSource.ToString() != null && errorProviderSame2.DataSource.ToString() != null)
{
if (errorProviderSame2.DataSource.ToString() == textBoxSvrcAtual.Name)
errorProviderSame2.Dispose();
if (errorProviderSame1.DataSource.ToString() == textBoxSvrcAtual.Name)
errorProviderSame1.Dispose();
}
Note: I run all of the validations in the text changed event and the "textBoxSvrcAtual" is the name of the textBox I am comparing to the errorProvide DataSource
Dispose does not delete an object. The actual deletion is done autmatically by the garbage collector, if there is no variable referencing the object any more.
Dispose is designed to do some clean up prematurely to the actual deletion of an object (e. g. releasing unmanaged memory, closing file descriptors or sockets, ...), see MSDN documentation and tutorial.
To really get the error provider deleted (at a point somewhere in the future), you have to set all references to it to null (or another ErrorProvider).
Either way (by disposing or by setting to null), you won't be able to appropriately use the provider any more afterwards – and if you still need an error provider for future validation, you will have to replace it with a new instance. I can imagine quite well that this not really is what you intended, possibly it is more appropriate for you just to clear the error (using SetError with empty string).
Attention: "The DataSource is a data source that you can attach to a control and that you want to monitor for errors. DataSource can be set to any collection that implements IList." (see MSDN). So you won't get what you expected.
You could instead set the Tag property to the text box and compare ep.Tag == tb
(no toString, no name, just directly the reference).