Search code examples
c#winformsuser-controlscomparisonerrorprovider

how to compare two textbox.text is greater than other textbox.text with error provider?


I put two textbox in user control in C# winform.txtFrom and txtTo. I want to compare two textbox.text and if txtTo is less than txtFrom , error provider are shown. how do I do?


Solution

  • You don't compare something with error provider. Error provider only shows that control has an error associated with control.

    • Add ErrorProvider component to your form
    • Compare txtFrom.Text and txtTo.Text (e.g. during Validating event)
    • If text is less (I don't know what less means for you), then call errorProvider1.SetError(txtTo, "Text is less than txtFrom"), otherwise call errorProvider1.SetError(txtTo, "")

    How to do comparison:

    errorProvider1.SetError(txtFrom, "");
    errorProvider1.SetError(txtTo, "");
    
    int fromValue;
    int toValue;
    
    if (!Int32.TryParse(txtFrom.Text, out fromValue)
    {
        errorProvider1.SetError(txtFrom, "Integer number required");
        return;
    }
    
    if (!Int32.TryParse(txtTo.Text, out toValue)
    {
        errorProvider1.SetError(txtTo, "Integer number required");
        return;
    }
    
    if (toValue < fromValue)
    {
        errorProvider1.SetError(txtTo, "To is less than From");
        return;
    }
    

    Consider also using NumericUpDown control to avoid text parsing stuff.