I want to create a user control, based on a textbox, that validates the input. I have tried it again and again but I don't know how to do this.
This is what I have come up with, but if there are other and better ways to do this, please let me know.
My big problem is the ValidTextBox() method. When I use this control on a form, I want to write a new method that does the actual validation for that specific control (e.g. checking if a field is empty). I tried with override, but that does NOT seem to work, because I get the error that there is no such function to override.
This is what I have come up with, but if there are other and better ways to do this, please let me know.
Code:
namespace soControls
{
public partial class MNLTextBox : TextBox
{
private string _OldValue;
private string _ErrorMessage1 = "";
private string _ErrorMessage2 = "";
private ErrorProvider TextBoxErrorProvider;
public MNLTextBox()
{
InitializeComponent();
this.Validating += new CancelEventHandler(MNLTextBox_Validating);
this.Validated += new EventHandler(MNLTextBox_Validated);
TextBoxErrorProvider = new ErrorProvider();
}
private void MNLTextBox_Validating(object sender, CancelEventArgs e)
{
if (this.Text != _OldValue)
{
if (ValidTextBox())
{
_OldValue = this.Text;
if (((MNLForm)MNLForm.ActiveForm).DBStatus == soSystem.cUnChanged)
((MNLForm)MNLForm.ActiveForm).DBStatus = soSystem.cEdit;
}
else
{
e.Cancel = true;
this.Select(0, this.Text.Length);
this.TextBoxErrorProvider.SetIconAlignment(this, ErrorIconAlignment.MiddleLeft);
this.TextBoxErrorProvider.SetError(this, (_ErrorMessage1.Length > 0 ? _ErrorMessage1 : "Unidentified Error") + (_ErrorMessage2.Length > 0 ? "\n" + _ErrorMessage2 : ""));
}
}
}
private void MNLTextBox_Validated(object sender, EventArgs e)
{
this.TextBoxErrorProvider.SetError(this, "");
}
public virtual Boolean ValidTextBox()
{
return true;
}
public string OldValue
{
get { return _OldValue; }
set { _OldValue = value; }
}
public string ErrorMessage1
{
get { return _ErrorMessage1; }
set { _ErrorMessage1 = value; }
}
public string ErrorMessage2
{
get { return _ErrorMessage2; }
set { _ErrorMessage2 = value; }
}
}
}
My big problem is the ValidTextBox() method. When I use this control on a form, I want to write a new method that does the actual validation for that specific control (e.g. checking if a field is empty). I tried with override, but that does NOT seem to work, because I get the error that there is no such function to override.