本文介绍了如何使MaskedTextBox中只接受十六进制值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个控制,只接受以下格式的十六进制值:

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

XXXX-XXXX 和x是0-9,AF,AF

xxxx-xxxx and x is in 0-9, a-f, A-F

所以,我想补充一个MaskedTextBox中并尝试编辑它的面膜属性,但没有成功。

So I add a MaskedTextBox and try to edit its Mask property, but did not succeed.

推荐答案

一个新类是需要验证,如果输入值是有效的,类类型应设置为MaskedTextBox1的ValidatingType属性如下:

A new class is need to verify if the value input is valid and the class type should be set as MaskedTextBox1's ValidatingType property, as following:

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

这篇关于如何使MaskedTextBox中只接受十六进制值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 12:11