【问题标题】:C# Convert Textbox Input to Int [duplicate]C#将文本框输入转换为Int [重复]
【发布时间】:2011-07-23 05:17:08
【问题描述】:

可能重复:
How can I convert String to Int?

我有一个用户可以输入数字的文本框,有没有办法将它转换为 int?因为我想将它插入到只接受 int 的数据库字段中。

tryParse 方法似乎不起作用,仍然抛出异常。

【问题讨论】:

    标签: c# string text


    【解决方案1】:
    private void txtAnswer_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (bNumeric && e.KeyChar > 31 && (e.KeyChar < '0' || e.KeyChar > '9'))
            {
                e.Handled = true;
            }
        }
    

    来源:http://www.monkeycancode.com/c-force-textbox-to-only-enter-number

    【讨论】:

      【解决方案2】:
      int orderID = 0;
      
      orderID = Int32.Parse(txtOrderID.Text);
      

      【讨论】:

        【解决方案3】:

        使用Int32.ParseInt32.TryParse 或者您可以使用System.Convert.ToInt32

        int intValue = 0;
        if(!Int32.TryParse(yourTextBox.Text, out intValue))
        {
            // handle the situation when the value in the text box couldn't be converted to int
        }
        

        Parse 和 TryParse 之间的区别非常明显。后者优雅地失败,而另一个如果无法将字符串解析为整数则会抛出异常。但是 Int32.Parse 和 System.Convert.ToInt32 之间的差异更加微妙,并且通常与特定于文化的解析问题有关。基本上是如何解释负数、小数和千位分隔符。

        【讨论】:

          【解决方案4】:

          如果这是 WinForms,您可以使用 NumericUpDown 控件。如果这是网络表单,我会使用 Int32.TryParse 方法以及输入框上的客户端数字过滤器。

          【讨论】:

            【解决方案5】:
            int temp;
            
            if (int.TryParse(TextBox1.Text, out temp))
               // Good to go
            else
               // display an error
            

            【讨论】:

              【解决方案6】:

              您可以使用Int32.Parse(myTextBox.text)

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2015-04-17
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2014-08-29
                • 2019-09-17
                相关资源
                最近更新 更多