【问题标题】:Allowing only Digits in a textbox not working? C#只允许文本框中的数字不起作用? C#
【发布时间】:2013-01-14 09:18:38
【问题描述】:

我有一个关于我正在进行的小型练习计划的问题。我几乎没有使用 C# 的经验,并且对 Visual Basic 有一点经验。我遇到的问题与仅允许文本框中的数字有关。我在另一个程序中成功地这样做了,但由于某种原因,它不能使用相对相同的代码。 这是代码:

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;
            }
        }
    }
} 

如果我的代码中还有其他错误,这里的任何人都可以纠正我,我也很感激。提前致谢。

【问题讨论】:

标签: c# textbox


【解决方案1】:

你已经把支票倒过来了。如果新字符是数字并且是控制字符,您的代码会取消输入。

if (!char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar))
    e.Handled = true;

【讨论】:

    【解决方案2】:

    你的逻辑不正确。它声明“如果按下的键是一个数字和一个控制字符......那么我已经处理了它”。你想要的是“如果按下的键是不是数字,我已经处理过了”。

    if (!char.IsNumber(e.KeyChar)) {
        // ...
    

    【讨论】:

    • 谢谢,我最初有 (!char 等) 但它似乎不起作用,所以我删除了它们并在放回它们之前发布在这里。出于某种原因,将“&&”行放在“!Char.IsNumber”行下后,它起作用了。
    【解决方案3】:
            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;
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-24
      • 1970-01-01
      • 2014-04-08
      • 1970-01-01
      • 2013-04-12
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      相关资源
      最近更新 更多