zoukankan      html  css  js  c++  java
  • Winform TextBox中只能输入数字的几种常用方法(C#)

    privatevoid tBox_KeyPress(object sender, KeyPressEventArgs e)
    {
    if (e.KeyChar ==0x20) e.KeyChar = (char)0; //禁止空格键
    if ((e.KeyChar ==0x2D) && (((TextBox)sender).Text.Length ==0)) return; //处理负数
    if (e.KeyChar >0x20)
    {
    try
    {
    double.Parse(((TextBox)sender).Text + e.KeyChar.ToString());
    }
    catch
    {
    e.KeyChar
    = (char)0; //处理非法字符
    }
    }
    }
    privatevoid TextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
    if(e.KeyChar!=8&&!Char.IsDigit(e.KeyChar))
    {
    e.Handled
    =true;
    }
    }
    或者private
    void TextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
    if(e.KeyChar!='\b'&&!Char.IsDigit(e.KeyChar))
    {
    e.Handled
    =true;
    }

    }


    privatevoid textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
    if(e.KeyChar!='\b')//这是允许输入退格键
    {
    if((e.KeyChar<'0')||(e.KeyChar>'9'))//这是允许输入0-9数字
    {
    e.Handled
    =true;
    }
    }
    }





    privatevoid button1_Click(object sender, EventArgs e)
    {
    string text =this.textBox1.Text;
    if (text !=null)
    MessageBox.Show(text);
    }

    privatevoid textBox1_Validating(object sender, CancelEventArgs e)
    {
    conststring pattern =@"^\d+\.?\d+$";
    string content = ((TextBox)sender).Text;

    if (!(Regex.IsMatch(content, pattern)))
    {
    errorProvider1.SetError((Control)sender,
    "只能输入数字!");
    e.Cancel
    =true;
    }
    else
    errorProvider1.SetError((Control)sender,
    null);
    }



    privatevoid textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
    if(e.KeyChar=='.'&&this.textBox1.Text.IndexOf(".")!=-1)
    {
    e.Handled
    =true;
    }

    if(!((e.KeyChar>=48&& e.KeyChar<=57) || e.KeyChar=='.'|| e.KeyChar==8))
    {
    e.Handled
    =true;
    }

    }



    privatevoid tbx_LsRegCapital_KeyPress(object sender, KeyPressEventArgs e)
    {
    if (!Char.IsNumber(e.KeyChar) &&!Char.IsPunctuation(e.KeyChar) &&!Char.IsControl(e.KeyChar))
    {
    e.Handled
    =true;//消除不合适字符
    }
    elseif (Char.IsPunctuation(e.KeyChar))
    {
    if (e.KeyChar !='.'||this.textBox1.Text.Length ==0)//小数点
    {
    e.Handled
    =true;
    }
    if (textBox1.Text.LastIndexOf('.') !=-1)
    {
    e.Handled
    =true;
    }
    }
    }







    利用ASCII码处理办法、
    {

    if ((e.KeyChar <=48|| e.KeyChar >=57) && (e.KeyChar !=8) && (e.KeyChar !=46))
    e.Handled
    =true;
    ================48代表0,57代表9,8代表空格,46代表小数点
    }

  • 相关阅读:
    Struts2-1.配置&与第一个应用
    1.rs.first()、rs.last()、rs.next()、rs.getRow()
    网页跳转
    js---DOM元素节点
    4、BufferedIn(out)putStream--->字节输入/输出流的缓冲区类(高效类:高效率读写)
    3、FileInputStream--->类文件输入流(读取文件数据)
    2、FileOutputStream--->文件输出流(向文件写入数据)
    1、IO输入&输出流 简介
    OutOfMemoryError系列
    Spark调优,性能优化
  • 原文地址:https://www.cnblogs.com/weipeng224/p/1734306.html
Copyright © 2011-2022 走看看