zoukankan      html  css  js  c++  java
  • 【转】WinForm中TextBox只能输入数字

    只能输入整数

    方法一

    private void tb_KeyPress(object sender, KeyPressEventArgs e)
    {
        //如果输入的不是退格和数字,则屏蔽输入
        if (!(e.KeyChar == '' || (e.KeyChar >= '0' && e.KeyChar <= '9')))
        {
            e.Handled = true;
        }
    }

    e.KeyChar >= ‘0’ && e.KeyChar <= ‘9’ //表示输入的是数字
    e.Handled = true; //true表示已经处理该事件,则屏蔽输入

    方法二

    private void tb_KeyPress(object sender, KeyPressEventArgs e)
    {
        //如果输入的不是退格和数字,则屏蔽输入
        if (!(e.KeyChar == 8 || (e.KeyChar >= 48 && e.KeyChar <= 57)))
        {
            e.Handled = true;
        }
    }

    8代表退格,48代表0,57代表9,46代表小数点

    方法三

    private void tb_KeyPress(object sender, KeyPressEventArgs e)
    {
        //如果输入的不是退格和十进制数字,则屏蔽输入
        if (!(e.KeyChar == '' || char.IsDigit(e.KeyChar)))
        {
            e.Handled = true;
        }
    }

    方法四

    private void tb_KeyPress(object sender, KeyPressEventArgs e)
    {
        //如果输入的不是退格且不能转为整数,则屏蔽输入
        if (!(e.KeyChar == '' || int.TryParse(((TextBox)sender).Text + e.KeyChar.ToString(), out int i)))
        {
            e.Handled = true;
        }
    }

    只能输入小数

    方法一

    private void tb_KeyPress(object sender, KeyPressEventArgs e)
    {
        //当前输入的是"."且(输入框已经有“.”或者文本框没有内容),则屏蔽输入
        if (e.KeyChar == '.' && (((TextBox)sender).Text.IndexOf(".") != -1 || ((TextBox)sender).Text.Length == 0))
        {
            e.Handled = true;
        }
        //如果输入的不是退格、数字和点,则屏蔽输入
        if (!(e.KeyChar == '' || (e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == '.'))
        {
            e.Handled = true;
        }
    }

    方法二

    private void tb_KeyPress(object sender, KeyPressEventArgs e)
    {
        //如果输入的不是退格且不能转为小数,则屏蔽输入
        if (!(e.KeyChar == '' || float.TryParse(((TextBox)sender).Text + e.KeyChar.ToString(), out float f)))
        {
            e.Handled = true;
        }
    }

    只能输入数字(包含负数)

    private void tb_KeyPress(object sender, KeyPressEventArgs e)
    {
        //如果输入的不是负号,退格且不能转为小数,则屏蔽输入
        if (!(e.KeyChar == '-'|| e.KeyChar == '' || float.TryParse(((TextBox)sender).Text + e.KeyChar.ToString(), out float f)))
        {
            e.Handled = true;
        }
    }

    本文转载自:https://blog.csdn.net/weixin_38211198/article/details/89214705

  • 相关阅读:
    Win10/UWP开发-Ink墨迹书写
    Win10/UWP 让你的App使用上扫描仪
    Win10/UWP新特性—Drag&Drop 拖出元素到其他App
    UWP/Win10新特性系列—Drag&Drop 拖动打开文件
    1、WIN2D学习记录(win2d实现JS雨天效果)
    Windows 通用应用尝试开发 “51单片机汇编”总结
    D2.Reactjs 操作事件、状态改变、路由
    D1.1.利用npm(webpack)构建基本reactJS项目
    UWP 动画系列之模仿网易云音乐动画
    字符设备驱动之Led驱动学习记录
  • 原文地址:https://www.cnblogs.com/lijigang/p/14049764.html
Copyright © 2011-2022 走看看