| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 9305 人关注过本帖, 3 人收藏
标题:[原创]关于强制让一个TextBox控件只能输入数字(含小数)的方法
只看楼主 加入收藏
C_B_Lu
Rank: 1
等 级:新手上路
威 望:1
帖 子:453
专家分:0
注 册:2006-1-10
收藏(3)
 问题点数:0 回复次数:16 
[原创]关于强制让一个TextBox控件只能输入数字(含小数)的方法

*/ --------------------------------------------------------------------------------------
*/ 出自: 编程中国 http://www.bc-cn.net
*/ 作者: C_B_Lu QQ:184118549
*/ 时间: 2007-9-20 编程论坛首发
*/ 声明: 尊重作者劳动,转载请保留本段文字
*/ --------------------------------------------------------------------------------------


自已尝试过很多次﹐每次都不是很理想﹐现在尝试将其做成一个用户控件﹐与大家分享﹐同时希望大家能提供出更好的方法﹒

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace WinERP
{
public partial class UC_DecimalTextBox : UserControl
{
private int intLength = 3; // 整数部份的长度
private int decimalLength = 2; // 保留小数的位数
private ErrorProvider errorProvider; // 用于显示错误信息的ErrorProvider控件

[Description("设置整数部份的长度(在1~100之间)")]
public int IntLength
{
get { return intLength; }
set
{
try
{
if (value < 1)
{
intLength = 1;
throw new Exception("整数部份的长序必须是1~100之间");
}
else if (value > 100)
{
intLength = 100;
throw new Exception("整数部份的长序必须是1~100之间");
}
else
{
intLength = value;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (decimalLength == 0)
{
textBox1.MaxLength = IntLength;
}
else
{
textBox1.MaxLength = intLength + decimalLength + 1;
}
}
}
}

[Description("设置小数部份的长度(在0~10之间)")]
public int DecimalLength
{
get { return decimalLength; }
set
{
try
{
if (value < 0)
{
decimalLength = 0;
throw new Exception("小数部份的长序必须0~10之间");
}
else if (value > 10)
{
decimalLength = 10;
throw new Exception("小数部份的长序必须0~10之间");
}
else
{
decimalLength = value;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (decimalLength == 0)
{
textBox1.MaxLength = IntLength;
}
else
{
textBox1.MaxLength = intLength + decimalLength + 1;
}
}
}
}

[Description("用于显示错误信息的ErrorProvider控件")]
public ErrorProvider ErrorProvider
{
get { return errorProvider; }
set { errorProvider = value; }
}

[Description("文本框的边框样式")]
public BorderStyle TextBoxBorderStyle
{
get { return textBox1.BorderStyle; }
set { textBox1.BorderStyle = value; }
}

[Description("表示如何对齐TextBox控件中的文字")]
public HorizontalAlignment TextAlign
{
get { return textBox1.TextAlign; }
set { textBox1.TextAlign = value; }
}

[Description("控制是否可以编辑TextBox中的文字")]
public bool ReadOnly
{
get { return textBox1.ReadOnly; }
set { textBox1.ReadOnly = value; }
}

[Description("文本框中的文字")]
public override string Text
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}

public UC_DecimalTextBox()
{
InitializeComponent();
}

// 当控件调整大小时发生
private void UC_DecimalTextBox_Resize(object sender, EventArgs e)
{
textBox1.Width = this.Width - 6;
this.Height = textBox1.Height + 6; // 固定自定义控件的高﹐不允许调大
}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar == '\b') || (e.KeyChar == '.'))
{
e.Handled = false; // 允许输入
int pos = textBox1.SelectionStart;
int intLength = textBox1.Text.Length;

if ((intLength == textBox1.MaxLength) && (pos < textBox1.MaxLength))
{
textBox1.SelectionLength = 1;
if ((textBox1.SelectedText == ".") && (e.KeyChar != '.'))
{
++textBox1.SelectionStart;
}
}

if ((e.KeyChar == '.') && (textBox1.Text.IndexOf('.') > -1))
{
e.Handled = true;
if ((pos < IntLength - 1) && (textBox1.Text.Substring(pos, 1) == "."))
{
textBox1.SelectionStart = ++pos;
}
}

if ((decimalLength == 0) && (e.KeyChar == '.')) // 如果是保留零位小数﹐则不允许输入点号
{
e.Handled = true;
}
}
else
{
e.Handled = true; // 不允许输入
}
}

private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
int pos = textBox1.SelectionStart;
string strValue = textBox1.Text.Trim();

if (decimalLength == 0)
{ // 当文本框中只输入整数时
while (strValue.Substring(0, 1) == "0")
{ // 去除整数部份最前右侧的
if (strValue.Length > 1)
{
strValue = strValue.Substring(1, strValue.Length - 1);
if (pos > 0)
{
--pos;
}
}
else
{
break;
}
}
textBox1.Text = strValue;
}
else
{ // 当文本框用于输入小数时
int pointPs = strValue.IndexOf('.');
if (pointPs < 0)
{
strValue += ".".PadRight(DecimalLength, '0');
}
if (pointPs == 0)
{
strValue = "0" + strValue;
textBox1.SelectionStart = ++pos;
}

// 自动使其保留两位小数
string[] strs = strValue.Split(new char[] { '.' });
strs[0] = strs[0].Length > 0 ? strs[0] : "0";

// 去除整数部份最前右侧的
while (strs[0].Substring(0, 1) == "0")
{
if (strs[0].Length > 1)
{
strs[0] = strs[0].Substring(1, strs[0].Length - 1);
if (pos > 0)
{
--pos;
}
}
else
{
break;
}
}

// 取得小数字数的数字,如果不足小数字长度﹐则以填补
if (strs[1].Length < decimalLength)
{
strs[1] = strs[1].PadRight(decimalLength, '0');
}

textBox1.Text = strs[0] + "." + strs[1];
}
textBox1.SelectionStart = pos;
}

private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (errorProvider == null)
{
return;
}
errorProvider.SetError(this, "");
double dValue;
if (!double.TryParse(textBox1.Text, out dValue))
{
string strMsg = string.Format("请输入整数部份不超过{0}位﹐且小数字不超过{1}位的有效数字!", IntLength, decimalLength);
if (decimalLength == 0)
{
strMsg = string.Format("请输入不超过{0}位的有效整数!", IntLength);
}
errorProvider.SetError(this, strMsg);
e.Cancel = true;
}
}
}
}

[此贴子已经被作者于2007-9-20 18:46:19编辑过]

搜索更多相关主题的帖子: TextBox 小数 控件 数字 输入 
2007-09-20 16:16
卡卡艾
Rank: 6Rank: 6
等 级:贵宾
威 望:22
帖 子:672
专家分:0
注 册:2007-4-3
收藏
得分:0 
我来顶一个.
支持原创.

革命尚未成功,同志仍需努力-----+++
2007-09-20 19:18
zhao601
Rank: 1
等 级:新手上路
帖 子:111
专家分:0
注 册:2005-8-26
收藏
得分:0 
太复杂了点,用正则表达式非常简单
2007-09-21 10:53
C_B_Lu
Rank: 1
等 级:新手上路
威 望:1
帖 子:453
专家分:0
注 册:2006-1-10
收藏
得分:0 
以下是引用zhao601在2007-9-21 10:53:16的发言:
太复杂了点,用正则表达式非常简单

自己不會寫正則表達式﹐能不能提供一個范例﹒


帮助那些真正需要帮助的人,是对帮助你的人最好的回报!
2007-09-21 13:36
咸蛋超人
Rank: 1
等 级:新手上路
帖 子:8
专家分:0
注 册:2007-12-10
收藏
得分:0 
LZ竟然忽略正则的强大.........不知道说什么好了.....
2007-12-12 09:48
沉沦过迁
Rank: 2
来 自:广西百色
等 级:论坛游民
帖 子:2297
专家分:10
注 册:2007-5-8
收藏
得分:0 
正则容易实现

也许我没有明天,但是我拥有现在
2007-12-12 10:04
tanxiaolin
Rank: 1
等 级:新手上路
帖 子:71
专家分:0
注 册:2007-12-12
收藏
得分:0 
强制只能输入数字,应该不用这么复杂吧
2007-12-12 10:09
blueskyss
Rank: 1
来 自:湖北
等 级:新手上路
帖 子:81
专家分:0
注 册:2008-2-19
收藏
得分:0 
namespace TempForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public bool isnum(string s)
        {
            for (int i = 2; i < s.Length; i++)
            {
                if (!char.IsNumber(s, i)&&!s[1]=='1')
                {
                    return false;
                }
            }
            return true;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if ((!isnum(textBox1.Text)) || textBox1.Text == "")
            {
                MessageBox.Show("请输入数字");
                return;
            }
            label1.Text += textBox1.Text;
        }
    }
}

[[it] 本帖最后由 blueskyss 于 2008-4-5 20:19 编辑 [/it]]
2008-04-05 13:27
wang232504
Rank: 1
等 级:新手上路
帖 子:23
专家分:0
注 册:2008-4-6
收藏
得分:0 
回复
正则表达式  去网上能找到很多格式的实例  查一下    否则别的方法  很麻烦的
2008-04-06 00:20
师妃暄
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:805
专家分:107
注 册:2006-3-1
收藏
得分:0 
完全不必要这样。正则表达式就能达到

有实力才会有魅力 实力来自坚持不懈的努力
2008-04-06 00:48
快速回复:[原创]关于强制让一个TextBox控件只能输入数字(含小数)的方法
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.016752 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved