开发者

C# Convert Textbox Input to Int [duplicate]

开发者 https://www.devze.com 2023-02-20 01:25 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How can I convert Str开发者_StackOverflow社区ing to Int?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How can I convert Str开发者_StackOverflow社区ing to Int?

I have a textbox that the user can put numbers in, is there a way to convert it to int? As I want to insert it into a database field that only accepts int.

The tryParse method doesn't seem to work, still throws exception.


Either use Int32.Parse or Int32.TryParse or you could use 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
}

The difference between Parse and TryParse is pretty obvious. The latter gracefully fails while the other will throw an exception if it can't parse the string into an integer. But the differences between Int32.Parse and System.Convert.ToInt32 are more subtle and generally have to do with culture-specific parsing issues. Basically how negative numbers and fractional and thousands separators are interpreted.


int temp;

if (int.TryParse(TextBox1.Text, out temp))
   // Good to go
else
   // display an error


You can use Int32.Parse(myTextBox.text)


If this is WinForms, you can use a NumericUpDown control. If this is webforms, I'd use the Int32.TryParse method along with a client-side numeric filter on the input box.


int orderID = 0;

orderID = Int32.Parse(txtOrderID.Text);


private void txtAnswer_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (bNumeric && e.KeyChar > 31 && (e.KeyChar < '0' || e.KeyChar > '9'))
        {
            e.Handled = true;
        }
    }

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

0

精彩评论

暂无评论...
验证码 换一张
取 消