Click here to Skip to main content
15,860,861 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
can someone help me how to check that the user pressed an int ?
Posted
Comments
Wonde Tadesse 30-Apr-11 14:39pm    
On what type of application you talking about. Is it web site, console, window ?

With the info you provided, I'd do something like this:

C#
static void Main()
{
    object o1 = 10;
    object o2 = "20";
    object o3 = new Object();

    Console.WriteLine(CheckForInt(o1));
    Console.WriteLine(CheckForInt(o2));
    Console.WriteLine(CheckForInt(o3));        }

private static bool CheckForInt(object o)
{
    int dummy;
    return o is Int32 || Int32.TryParse(o.ToString(), out dummy);
}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 30-Apr-11 17:23pm    
I'm not sure this is what required, but I like the elegance of "||" instead of "&&". All correct, my 5.
--SA
Nish Nishant 30-Apr-11 17:48pm    
Thank you, SA!
It depends of where you entered the data, and when you whan to check if it is an int but with a textbox and checking everytime yo press a key may be something like this, add with VS a Keyup event to textbox and check the textBox.Text, then do what you need.




C#
this.textBox.KeyUp += new System.Windows.Forms.KeyEventHandler(this.textBox_KeyUp);


private void textBox2_KeyUp(object sender, KeyEventArgs e)
{
    int _integer;
    if (!int.TryParse(textBox2.Text, out _integer)) MessageBox.Show("Not Int");
}


This is to check if whole data is a number, if you want to check key by key you can play with e.KeyCode.ToString().
Regards
 
Share this answer
 
v3
Comments
anyavacy 1-May-11 6:38am    
this is it, thank you
For C# console:
C#
bool result = Int32.TryParse(value, out number);
  if (result)
  {
     Console.WriteLine("Converted '{0}' to {1}.", value, number);
  }

OR
C# Validating TextBox Control[^]

For asp.net, call any of the javascript functions :

Example 1:
C#
function is_int(value){
   for (i = 0 ; i < value.length ; i++) {
      if ((value.charAt(i) < '0') || (value.charAt(i) > '9')) return false
    }
   return true;
}

Example 2 :
SQL
function is_int(value){
   return !isNaN(parseInt(value * 1)
}

Example 3:
C#
function is_int(value){
  if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
      return true;
  } else {
      return false;
  }
}


I hope the above information will be helpful. If you have more concerns, please let me know.
 
Share this answer
 
Comments
RaviRanjanKr 30-Apr-11 15:03pm    
Nice Answer! My 5 :)
Monjurul Habib 30-Apr-11 15:04pm    
thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900