Integer Parsing

I need to write a confirmation for a text field whose value is <= 2147483647

my code looks something like this:

Textbox1.Text = "78987162789"

if(Int32.Parse(Textbox1.text) > 2147483647)
{
  Messagebox("should not > ")
}

I get an error: value is too small or too big for Int. How can i fix this?

+3
source share
5 answers

There is a TryParsemethod that is best suited for this purpose.

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

32 , 32 , ; 31, . , , 2^31 - 1, . 2147483647. 78987162789 > 2147483648, .

long.

Edit:

, long 9,223,372,036,854,775,807 (2 ^ 63 - 1), . , , Int32.TryParse - , , , .

+3
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.
}
0

The error occurs because 78987162789 is greater than 2 ^ 31, so it is too large for Int32. As suggested, use the TryParse method and continue if it returns true.

0
source

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
source

Source: https://habr.com/ru/post/1723185/


All Articles