65.9K
CodeProject 正在变化。 阅读更多。
Home

自定义控件:数字文本框:只允许输入数字的文本框

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.10/5 (9投票s)

2007年1月29日

viewsIcon

56295

有时我们需要控制用户输入到特定值。以下文章解释了如何使用文本框来实现这一点。

引言

有时我们需要控制用户输入。这个控件是一个普通的文本框,其属性是该控件接受数字值!

因为这个控件是一个文本框,所以我们像这样从基类继承:NumericTextBox : TextBox

我们需要做的是重写 OnKeyPress 和 OnKeyDown 事件。完整的代码如下

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

namespace MyCustomControls
{
    [Description("Numeric TextBox")]
    public class NumericTextBox : TextBox
    {
        private bool nonNumberEntered = false;

        public NumericTextBox()
        {
            this.Width = 150;
        }

        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            if (nonNumberEntered == true)
            {
                e.Handled = true;
            }
        }
        protected override void OnKeyDown(KeyEventArgs e)
        {
            nonNumberEntered = false;
            if (e.Shift == true || e.Alt == true)
            {
                nonNumberEntered = true;
                return;
            }
            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
            {
                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                {
                    if (e.KeyCode != Keys.Back)
                    {
                        nonNumberEntered = true;
                    }
                }
            }
        }
    }
}



现在,我们只需要在我们的应用程序中使用它了。
这段代码还可以改进。现在可以从剪贴板粘贴非数字值。下一个版本(我将在几天内编写)将包含这些改进!

© . All rights reserved.