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

  • 相关阅读:
    2-SAT
    CDQ分治
    整体二分
    未完成
    [BZOJ1857][SCOI2010]传送带-[三分]
    [LCT应用]
    [胡泽聪 趣题选讲]大包子环绕宝藏-[状压dp]
    [清华集训2015 Day2]矩阵变换-[稳定婚姻模型]
    [清华集训2015 Day1]主旋律-[状压dp+容斥]
    [清华集训2015 Day1]玛里苟斯-[线性基]
  • 原文地址:https://www.cnblogs.com/lijigang/p/14049764.html
Copyright © 2011-2022 走看看