How to make MaskedTextBox accept only HEX value?

I need a control that accepts a HEX value only in the following format:

xxxx-xxxx and x is at 0-9, af, AF

So, I add MaskedTextBox and try to change its Mask property , but failed.

+3
source share
2 answers

The new class should check if the value is actually entered, and the class type should be set as the MaskedTextBox1 ValidatingType property, as shown below:

public class HexValidator
{
. . .

// the following function is needed to used to verify the input
public static HexValidator Parse(string s)
{
 // remove any spaces
            s = s.Replace(" ", "");

            string[] strParts = s.Split('-');
            int nValue;

            foreach (string part in strParts)
            {
                bool result = int.TryParse(part, System.Globalization.NumberStyles.AllowHexSpecifier, null, out nValue);
                if (false == result)
                    throw new ArgumentException(string.Format("The provided string {0} is not a valid subnet ID.", s));
            }

            return new SubnetID(strParts[0], strParts[1]);
}
}

/// set as following to associate them
maskedTextBox1.ValidatingType = typeof(HexValidator);

// in  the validationcomplete event, you could judge if the input is valid
private void maskedTextBox1_TypeValidationCompleted(object sender, TypeValidationEventArgs e)
        {
            if (e.IsValidInput)
            {
                //AppendLog("Type validation succeeded.  Message: " + e.Message);                
            }
            else
            {
                toolTip1.Show(e.Message, maskedTextBox1, maskedTextBox1.Location, 5000);
            }
        }
+2
source
+2

Source: https://habr.com/ru/post/1739428/


All Articles