private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
string str = Regex.IsMatch(e.KeyCode.ToString(), "^OemPeriod|Decimal$") ? this.textBox1.Text + "." : this.textBox1.Text; if (
(this.textBox1.Text.Length == 0 && Regex.IsMatch(e.KeyCode.ToString(), "^OemPeriod|Decimal$"))
|| !Regex.IsMatch(e.KeyCode.ToString(), "^((D|NumPad)\\d|(Back|OemPeriod|Decimal))$")
|| (!(str.IndexOf(".") == str.LastIndexOf(".")) && str.IndexOf(".") != -1))
{
e.SuppressKeyPress = true;
}
}
上面的代码实现了验证首字符不能为小数点,且只能输入数字和小数点,删除键,
现在还差验证小数点后面的字符不能超过2位数,试了好多办法都没有成功,希望大牛可以帮帮忙~
在原代码的集成上实现。
解决方案 »
- url重写问题
- 算法问题
- .NET连接Oracle数据库的问题
- menuStrip多次点击问题
- 求只能输入1-31和99这32个数的正则表达式
- 听说DataBinder.Eval()性能低,要少用,为什么我直接使用数据绑定语句出错呢?请大家进来看看?
- 数据库备份问题请教(C# SQLSERVER2000)
- 如何连接数据库并将它的具体内容借助TreeView控件在dataGrid中显示出来
- 使用DI解耦服务层与UI层,用什么方法可以传入UI层的上下文信息?
- Borland Together Visual Studio.NET是干什么用的?
- 做了站点 后台数据库是mssql2005,打开页面时如何访问数据库?
- C#中如何将object类型转化为整型
string str = Regex.IsMatch(e.KeyCode.ToString(), "^OemPeriod|Decimal$") ? this.textBox1.Text + "." : this.textBox1.Text;
if(str.Length>0)
{
str =str.Length>3?"":str;
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
string str = Regex.IsMatch(e.KeyCode.ToString(), "^OemPeriod|Decimal$") ? this.textBox1.Text + "." : this.textBox1.Text;
if (
(this.textBox1.Text.Length == 0 && Regex.IsMatch(e.KeyCode.ToString(), "^OemPeriod|Decimal$"))
|| !Regex.IsMatch(e.KeyCode.ToString(), "^((D|NumPad)\\d|(Back|OemPeriod|Decimal))$")
|| (!(str.IndexOf(".") == str.LastIndexOf(".")) && str.IndexOf(".") != -1)
|| (e.KeyCode == Keys.Back ? 0 : str.IndexOf(".") == -1 ? 0 : str.Substring(str.IndexOf(".")).ToString().Length) == 3)
{
e.SuppressKeyPress = true;
}
}
搞定了~代码贴上来和大家分享下~
不知道大家还有没有其他更方便一点的方法~
就是在文本框输入的时候验证输入的值是否符合货币类型~
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
// 验证文本框输入字符是否为货币型
string str = Regex.IsMatch(e.KeyCode.ToString(), "^OemPeriod|Decimal$") ? this.textBox1.Text + "." : this.textBox1.Text;
if (
(this.textBox1.Text.Length == 0 && Regex.IsMatch(e.KeyCode.ToString(), "^OemPeriod|Decimal$"))
|| !Regex.IsMatch(e.KeyCode.ToString(), "^((D|NumPad)\\d|(Back|OemPeriod|Decimal))$")
|| (!(str.IndexOf(".") == str.LastIndexOf(".")) && str.IndexOf(".") != -1)
|| (str.IndexOf("0") == 0 && Regex.IsMatch(e.KeyCode.ToString(), "^(D|NumPad)0$"))
|| (e.KeyCode == Keys.Back ? 0 : str.IndexOf(".") == -1 ? 0 : str.Substring(str.IndexOf(".")).ToString().Length) == 3)
{
e.SuppressKeyPress = true;
}这样就可以了~不过感觉代码有点多~大牛帮忙精简下哇~