您的位置:首页 > 其它

限制只能输入整数、小数的输入框

2015-01-21 10:09 417 查看
1.支持整数和小数两种输入方式 2.可以通过VS的属性窗口,设置<span style="font-family: Arial, Helvetica, sans-serif;">InputType属性来选择是哪种输入方式</span>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace UserController {
public partial class IntegerInput : TextBox {

public enum InputTypeEnum {
IntegerType = 0,
DobuleType = 1
}
private InputTypeEnum inputType;
public InputTypeEnum InputType {
get { return inputType; }
set { inputType = value; }
}

public IntegerInput() {
InitializeComponent();
}

public IntegerInput(IContainer container) {
container.Add(this);
InitializeComponent();
}

protected override void OnKeyPress(KeyPressEventArgs e) {
base.OnKeyPress(e);
int kc = e.KeyChar;
if (InputTypeEnum.IntegerType == InputType) {
IntegerType(kc, e);
} else {
DobuleType(kc, e);
}
}

private void IntegerType(int kc,KeyPressEventArgs e) {
if (kc == (char)8 || (kc >= '0' && kc <= '9')) {
e.Handled = false;
} else {
e.Handled = true;
}
}

private void DobuleType(int kc, KeyPressEventArgs e) {
if (kc == (char)8 || (kc >= '0' && kc <= '9')) {
e.Handled = false;
} else if (kc == 46) {
if (this.Text.Length <= 0)
e.Handled = true;           //小数点不能在第一位
else {
float f;
float oldf;
bool b1 = false, b2 = false;
b1 = float.TryParse(this.Text, out oldf);
b2 = float.TryParse(this.Text + e.KeyChar.ToString(), out f);
if (b2 == false) {
if (b1 == true)
e.Handled = true;
else
e.Handled = false;
}
}
} else {
e.Handled = true;
}
}
}
}


其中,小数输入代码借鉴网络
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: