【问题标题】:C# windows forms - How can I only allow integers to be input into textboxes? [duplicate]C# windows 窗体 - 如何只允许将整数输入到文本框中? [复制]
【发布时间】:2017-09-15 00:09:06
【问题描述】:

我是 C# 的新手,这是我第一次尝试创建 Windows 窗体。我创建了一个非常简单的计算器,它有两个文本框供用户输入数字。它有一个(n)加、减、乘和除按钮,当用户在文本框中输入值并单击其中一个按钮时,结果会显示在标签中。我只想允许将整数输入到文本框中,但我不知道我将如何做到这一点。任何意见或建议表示赞赏。谢谢。

到目前为止,这是我的代码:

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

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void AddBtn_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
            ResultLbl.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString();
    }

    private void SubtractBtn_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
            ResultLbl.Text = (Convert.ToInt32(textBox1.Text) - Convert.ToInt32(textBox2.Text)).ToString();
    }

    private void MultiplyBtn_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
            ResultLbl.Text = (Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox2.Text)).ToString();
    }

    private void DivideBtn_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
            ResultLbl.Text = (Convert.ToInt32(textBox1.Text) / Convert.ToInt32(textBox2.Text)).ToString();
    }
}

}

【问题讨论】:

  • 如果是计算器,NumericUpDowns 可能更合适。它们仍然不是整数,但不允许字母。请阅读How to Ask 并采取tour

标签: c# winforms


【解决方案1】:

您可以使用下面的函数,并将其添加到文本框的按键事件中。

private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

【讨论】:

    【解决方案2】:

    最简单的方法是使用 NumericUpDown 控件代替 TextBox。 NumericUpDown 只允许数字作为输入,并且具有与 TextBox 类似的属性。

    像这样访问值:

    decimal answer=numericUpDown1.Value
    

    `

    【讨论】:

      【解决方案3】:

      使用NumericUpDown

      你可以在这里找到一个类似的问题How do I make a textbox that only accepts numbers?

      【讨论】:

        【解决方案4】:

        简单点试试这个

        //function
        public static void NumberOnly(object sender, KeyPressEventArgs e)
        {
             e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
        }
        
        //to call used this
        NumberOnly("your textbox");
        

        【讨论】:

          猜你喜欢
          • 2018-10-23
          • 2016-03-04
          • 2011-11-09
          • 1970-01-01
          • 1970-01-01
          • 2013-04-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多