博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

NumericUpDown控件的一个bug

Posted on 2010-03-11 13:49  Harry Huang  阅读(838)  评论(0编辑  收藏  举报

前一段时间在使用NumericUpDown的时候,发现了一个在设置Hexcadecimal为True时候的bug:

即使设置Maximum为4294967295(0xFFFFFFFF),但是控件也不接受大于2147483647(0x7FFFFFFF)的数。

 

后来在http://social.msdn.microsoft.com/forums/en-US/winforms/thread/6eea9c6c-a43c-4ef1-a7a3-de95e17e77a8/上查询得知NumericUpDown使用Convert.ToInt32()来转换输入的文本,因此大于0x7FFFFFFF的数值将得到负数,导致控件不接受输入的值。

 

解决的方式是从NumericUpDown继承写一个HexNumericUpDown控件来解决问题,代码如下:

using System;
using System.ComponentModel;
using System.Windows.Forms;


public class HexNumericUpDown : NumericUpDown
{
    [Browsable(false)]
    public new bool Hexadecimal
    {
        get
        {
            return base.Hexadecimal;
        }
        set
        {
            base.Hexadecimal = value;
        }
    }

    public HexNumericUpDown()
    {
        base.Hexadecimal = false;
        base.Minimum = 0;
        base.Maximum = UInt32.MaxValue;
    }
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]

    public new decimal Maximum
    {
        // Doesn't serialize properly 
        get { return base.Maximum; }
        set { base.Maximum = value; }
    }

    protected override void UpdateEditText()
    {
        if (base.UserEdit == true)
        {
            HexParseEditText();
        }

        if (string.IsNullOrEmpty(base.Text) == false)
        {
            base.ChangingText = true;
            base.Text = string.Format("{0:X}", (uint)base.Value);
        }
    }

    protected override void ValidateEditText()
    {
        HexParseEditText();
        UpdateEditText();
    }

    private void HexParseEditText()
    {
        try
        {
            if (string.IsNullOrEmpty(base.Text) == false)
            {
                this.Value = Convert.ToInt64(base.Text, 16);
            }
        }
        catch
        {
        }
        finally
        {
            base.UserEdit = false;
        }
    }
}