文本框为等号,但文本框接受字母

时间:2019-05-11 07:16:20

标签: vb.net

我在文本框中使用数字,但是如果输入字母,则文本框也可以接受

If IsNumeric(TextBox1.TextLength = 0) Then
            MeanCalculateForm.Show()
            MeanCalculateForm.TextBox1.Text = TextBox1.Text
        Else
            MessageBox.Show("Please Enter Only Number !!!!", "Error 
Message Alphabet")
                TextBox1.Text = ""

            End If

图片屏幕截图-
https://ibb.co/PQb7zhz

2 个答案:

答案 0 :(得分:0)

您要寻找的正则表达式,在文本框的KeyDown事件上使用它,一个简单的用例就是

  

/ ^-?(0 | [1-9] \ d *)(。\ d +)?$ /

该正则表达式仅允许使用数字值(也适用于负数和小数)

var regex = new Regex(@"/^-?(0|[1-9]\d*)(\.\d+)?$/");
if(regex.IsMatch("Your character here")
{
   //allow the value to go through
}
else
{
   //set event as handled in your method
   //assuming args even is e
   e.IsHandled = true;
}

答案 1 :(得分:0)

在按键事件中尝试此操作

    public Form1()
    {
        InitializeComponent();
        SerialPortProgram();
    }

    private void SerialPortProgram()
    {
        SerialPort mySerialPort = new SerialPort("COM2");

        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;

        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
        mySerialPort.Open();
        mySerialPort.Close();
    }

    private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        switch (ASCIItoHex(indata))
        {
            case "00000113":
                LB_Display.Text = "User 1";
                break;
            case "0000017a":
                LB_Display.Text = "User 2";
                break;
            default:
                LB_Display.Text = "Disconnect";
                break;
        }
    }

    public static string ASCIItoHex(string Value)
    {
        StringBuilder sb = new StringBuilder();
        foreach (byte b in Value)
            sb.Append(string.Format("{0:x2}", b));
        return sb.ToString();
    }