如何使MaskedTextBox只接受HEX值?

时间:2010-04-01 06:49:38

标签: .net controls

我需要一个只接受以下格式的HEX值的控件:

xxxx-xxxx ,x位于0-9,a-f,A-F

所以我添加了一个MaskedTextBox并尝试编辑其 Mask 属性,但没有成功。

2 个答案:

答案 0 :(得分:3)

您无法使用MaskedTextBox开箱即用。如果您查看the documentation for the Mask property中详细说明的允许屏蔽元素,您将看到无法仅强制执行十六进制输入。

您可以使用NumericUpDown并将其Hexadecimal属性设置为true

答案 1 :(得分:2)

需要验证新类是否有效且类类型应设置为MaskedTextBox1的ValidatingType属性,如下所示:

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);
            }
        }