C# 输入框 价格框只允许数字输入,且只能输入两位数。
最编程
2024-03-03 21:46:16
...
//小数点只能 输入两位
private void txt_price_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != (char)('.') && e.KeyChar != (char)('-'))
{
e.Handled = true;
}
if (e.KeyChar == (char)('-'))
{
if ((sender as TextBox).Text != "")
{
e.Handled = true;
}
}
//第1位是负号时候、第2位小数点不可
if (((TextBox)sender).Text == "-" && e.KeyChar == (char)('.'))
{
e.Handled = true;
}
//负号只能1次
if (e.KeyChar == 45 && (((TextBox)sender).SelectionStart != 0 || ((TextBox)sender).Text.IndexOf("-") >= 0))
e.Handled = true;
//第1位小数点不可
if (e.KeyChar == (char)('.') && ((TextBox)sender).Text == "")
{
e.Handled = true;
}
//小数点只能1次
if (e.KeyChar == (char)('.') && ((TextBox)sender).Text.IndexOf('.') != -1)
{
e.Handled = true;
}
//小数点(最大到2位)
if (e.KeyChar != '\b' && (((TextBox)sender).SelectionStart) > (((TextBox)sender).Text.LastIndexOf('.')) + 2 && ((TextBox)sender).Text.IndexOf(".") >= 0)
e.Handled = true;
//光标在小数点右侧时候判断
if (e.KeyChar != '\b' && ((TextBox)sender).SelectionStart >= (((TextBox)sender).Text.LastIndexOf('.')) && ((TextBox)sender).Text.IndexOf(".") >= 0)
{
if ((((TextBox)sender).SelectionStart) == (((TextBox)sender).Text.LastIndexOf('.')) + 1)
{
if ((((TextBox)sender).Text.Length).ToString() == (((TextBox)sender).Text.IndexOf(".") + 3).ToString())
e.Handled = true;
}
if ((((TextBox)sender).SelectionStart) == (((TextBox)sender).Text.LastIndexOf('.')) + 2)
{
if ((((TextBox)sender).Text.Length - 3).ToString() == ((TextBox)sender).Text.IndexOf(".").ToString()) e.Handled = true;
}
}
//第1位是0,第2位必须是小数点
if (e.KeyChar != (char)('.') && e.KeyChar != 8 && ((TextBox)sender).Text == "0")
{
e.Handled = true;
}
}
上一篇: 淘宝购物车5年来的技术升级与沉淀
下一篇: 系统架构蓝图 - 抽象类