textBox 只能输入数字负号和小数点

qq_41948461 2018-06-02 04:17:54
private void CheckValue(KeyPressEventArgs e, TextBox txt)
{
if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)
e.Handled = true;
if (e.KeyChar == 45 && (((TextBox)txt).SelectionStart != 0 || ((TextBox)txt).Text.IndexOf("-") >= 0))
e.Handled = true;
if ((int)e.KeyChar == 46)
{
if (txt.Text.Length <= 0)
e.Handled = true;
else
{
float f;
float oldf;
bool b1 = false, b2 = false;
b1 = float.TryParse(txt.Text, out oldf);
b2 = float.TryParse(txt.Text + e.KeyChar.ToString(), out f);
if (b2 == false)
{
if (b1 == true)
e.Handled = true;
else
e.Handled = false;
}
}
}
}
这样写的但是不能输入负号,百度到的基本都是这样。能解释下为什么不能输入负号的嘛
...全文
700 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
xuzuning 2018-06-02
  • 打赏
  • 举报
回复
粗略的,这样就可以了
引用
private void CheckValue(KeyPressEventArgs e, TextBox txt) { Text = ((int)e.KeyChar).ToString(); double n; if (! double.TryParse(txt.Text + e.KeyChar.ToString() + "0", out n)) { e.Handled = true; } if (e.KeyChar == 8) e.Handled = false; }
xuzuning 2018-06-02
  • 打赏
  • 举报
回复
e.Handled = true; 时,将丢弃当前的按键 你自己分析一下就知道问题在哪了

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧