textbox 控制输入整数,小数
2024-10-18 23:26:58
/// <summary>
/// keypress事件控制输入
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void decimal_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == '.' ||
e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Delete)
{
int precision = 3;
int scale = 0;
TextBox textBox = sender as TextBox;
if ((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == '.')
{
if (scale == 0 && e.KeyChar == '.')
{
// 没有小数部的时候,小数点输入不可
e.Handled = true;
}
else if (textBox.Text.Contains(".") && e.KeyChar == '.')
{
// 已经输入'.'的时候,'.'输入不可
e.Handled = true;
}
else
{
// 除开上面的情况,对整数部和小数部的位数检查
string newString = textBox.Text.Substring(0, textBox.SelectionStart) + e.KeyChar +
textBox.Text.Substring(textBox.SelectionStart + textBox.SelectionLength);
if (newString.Contains("."))
{
// 有小数点的时候
string[] splits = newString.Split('.');
if (splits.Length > 1)
{
if (splits[0].Length > precision)
{
e.Handled = true;
}
else if (splits[1].Length > scale)
{
e.Handled = true;
}
}
}
else
{
// 没有小数点的时候
if (newString.Length > precision)
{
e.Handled = true;
}
}
}
}
}
else
{
// 数字以外输入的时候
e.Handled = true;
}
}
最新文章
- 谁说JavaScript容易?
- 精通visual c++指纹模式识别系统算法及实现
- HTML转义字符大全
- ASP.NET 5 Beta8发布及升级经验
- 重签名问题:does not have a signature matching
- 【CSS3】CSS3 滤镜实现
- 在windows下用toolbox玩会docker
- c#与vb.net在App_Code里面编译要通过,需要以下web.config的配置
- 高性能的JavaScript -- 读书笔记
- Python学习笔记一--字符串的使用
- OC随笔一:类
- 03-es6语法 Promise 和 es8语法 async await 的了解和基本使用
- python操作MongoDB、MySQL、Postgres、Sqlite、redis实例
- vue 无限递归级联组件实现方案
- Java数据类型(Primivite 和引用数据类型!)
- Tesseract-OCR4.0版本在VS2015上的编译与运行(转)
- axios 的应用
- C#正则表达式提取HTML中IMG标签的SRC地址
- Memcached和Memcache 配置教程windows X64
- BZOJ4735 你的生命已如风中残烛 【数学】