textbox只允许输入金额

最近老师傅让我帮他搞wpf的项目,我还是饶有兴趣的,要知道wpf在C/S端可是很受欢迎啊,我索性也就接过了,废话不多说,其中有一个textbox的控件,是输入金额的,查了很多参照了一些博客https://www.cnblogs.com/yuzhou133/p/4112539.html
其中调用部分应该用在哪呢?看我的博客吧,反正小编是成功了

private void txtsite_KeyDown(object sender, KeyEventArgs e)
{
    e.SuppressKeyPress = true;

     switch (e.KeyCode)
     {
         case Keys.D0:
         case Keys.D1:
         case Keys.D2:
         case Keys.D3:
         case Keys.D4:
         case Keys.D5:
         case Keys.D6:
         case Keys.D7:
         case Keys.D8:
         case Keys.D9:
         case Keys.NumPad0:
         case Keys.NumPad1:
         case Keys.NumPad2:
         case Keys.NumPad3:
         case Keys.NumPad4:
         case Keys.NumPad5:
         case Keys.NumPad6:
         case Keys.NumPad7:
         case Keys.NumPad8:
         case Keys.NumPad9:
         case Keys.Back:
         case Keys.OemPeriod:
         case Keys.Delete:
         case Keys.Decimal:
             e.SuppressKeyPress = false;
             break;
         default:
             break;
     }
}

private void txtsite_KeyPress(object sender, KeyPressEventArgs e)
{
    TextBox tBox = sender as TextBox;
     char c = e.KeyChar;

     if (c.ToString().Equals("."))
     {
         if (tBox.Text.Length <= 0)
             e.Handled = true;           //小数点不能在第一位     
         else
         {
             float f;
             float oldf;
             bool b1 = false, b2 = false;
             b1 = float.TryParse(tBox.Text, out oldf);
             b2 = float.TryParse(tBox.Text + e.KeyChar.ToString(), out f);
             if (b2 == false)
             {
                 if (b1 == true)
                     e.Handled = true;
                 else
                     e.Handled = false;
             }
         }
     }
     ShieldNumberTextBoxOtherKeys(tBox);//在此处调用即可
}

public virtual void ShieldNumberTextBoxOtherKeys(TextBox tbox)
{
    tbox.ImeMode = ImeMode.Disable;
    tbox.KeyDown += txtsite_KeyDown;
    tbox.KeyPress += txtsite_KeyPress;
}

寻寻觅觅,小编昨天在做这个功能的时候突然发现这个功能是有问题的,即第一次录入信息的时候录入的是汉字也可以录入,小编真是炸了,然后又查找了一些资料,参考地址https://bbs.csdn.net/topics/240038271?list=lz

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!(Char.IsNumber(e.KeyChar) || e.KeyChar == '\b' || e.KeyChar == '.'))
    {
        e.Handled = true;
      // MessageBox.Show("请输入数字");
    }
}

就是这么简单,小编在做的时候发现弹出提示会有重复,因此小编直接将弹出的提示屏蔽掉了,效果也是不错的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值