开发者

Integer parsing

I need to write a validation for a textbox which value is < = 2147483647

my code is something like:

Textbox1.Text = "78987162789"

if(Int32.Parse(Textbox1.text) > 2147483647开发者_如何学Go)
{
  Messagebox("should not > ")
}

I am getting error message something like: value is too small or too big for Int. How can I fix this?


There's a TryParse method which is better for that purpose.

int Val;
bool ok = Int32.TryParse (Textbox1.Text, out Val);
if (!ok) { ... problem occurred ... }


Integers are stored using 32 bits, so you only have 32 bits with which to represent your data; 31 once you take into account negative numbers. So numbers that are larger than 2^31 - 1 cannot be represented as integers. That number is 2147483647. So since 78987162789 > 2147483648, it cannot convert it to an integer.

Try using a long instead.

Edit:

Of course, long only works up to 9,223,372,036,854,775,807 (2 ^ 63 - 1), so you may end up in the same problem. So, as other people have suggested, use Int32.TryParse - if that fails, you can assume it's not a number, or it's bigger than your limit.


The error occurs because 78987162789 is greater than 2^31, so it's too big for an Int32. As suggested, use the TryParse method, and only proceed if it returns true.


Int64 result;
if (!Int64.TryParse(Textbox1.Text, out result))
{
    // The value is not a number or cannot be stored in a 64-bit integer.
}
else if (result > (Int64)Int32.MaxValue)
{
    // The value cannot be stored in a 32-bit integer.
}


You can use the Validating event.

private void textbox1_Validating(object sender, CancelEventArgs e)
{
    try
    {
        Int64 numberEntered = Int64.Parse(textBox1.Text);
        if (numberEntered > 2147483647)
        {
            e.Cancel = true;
            MessageBox.Show("You have to enter number up to 2147483647");
        }
    }
    catch (FormatException)
    {
        e.Cancel = true;
        MessageBox.Show("You need to enter a valid integer");
    }
}



    private void InitializeComponent()
    {

        // 
        // more code
        // 
        this.Textbox1.Validating += new System.ComponentModel.CancelEventHandler(this.textbox1_Validating);
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜