Allowing only Digits in a textbox not working? C#

2019-09-18 02:51发布

I have a question about a small practice program I'm working on. I have almost no experience with C#, and a little bit of experience with Visual Basic. The problem I'm having has to do with only allowing numbers in the text box. I succeeded in doing so in another program, but for some reason it isn't working with relatively the same code. Here is the code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            Double TextBoxValue;
            TextBoxValue = Convert.ToDouble(txtMinutes.Text);
            TextBoxValue = Double.Parse(txtMinutes.Text);

            {
                Double Answer;
                if (TextBoxValue > 59.99)
                {
                    Answer = TextBoxValue / 60;
                }
                else
                {
                    Answer = 0;
                }
                {
                    lblAnswer.Text = Answer.ToString();
                }
            }

        }

        private void txtHours_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsNumber (e.KeyChar) && Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }
    }
} 

If there are other errors in my code that anyone here can correct me on, that is also appreciated. Thanks in advance.

标签: c# textbox
3条回答
Bombasti
2楼-- · 2019-09-18 03:09

Your logic is incorrect. It states "if the pressed key is a number and a control character.. then i've handled it". What you want is "if the pressed key is NOT a number, I've handled it".

if (!char.IsNumber(e.KeyChar)) {
    // ...
查看更多
小情绪 Triste *
3楼-- · 2019-09-18 03:09
        private void txtHours_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
                && !char.IsDigit(e.KeyChar)
                && e.KeyChar != '.')
                e.Handled = true;

            // only allow one decimal point
            if (e.KeyChar == '.'
                && (txtHours).Text.IndexOf('.') > -1)
                e.Handled = true;
        }
查看更多
做自己的国王
4楼-- · 2019-09-18 03:18

You've got the checks inverted. What your code does is to cancel input if the new character is a number AND if it's a control character.

if (!char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar))
    e.Handled = true;
查看更多
登录 后发表回答