I\'d like to know on C# how to check if a string is a number (and just a number).
Example :
141241 Yes
232a23 No
12412a No
an
Many datatypes have a TryParse-method that will return true if it managed to successfully convert to that specific type, with the parsed value as an out-parameter.
In your case these might be of interest:
http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx
http://msdn.microsoft.com/en-us/library/system.decimal.tryparse.aspx
Regex.IsMatch(stringToBeChecked, @"^\d+$")
Regex.IsMatch("141241", @"^\d+$") // True
Regex.IsMatch("232a23", @"^\d+$") // False
Regex.IsMatch("12412a", @"^\d+$") // False
Perhaps you're looking for the int.TryParse
function.
http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx
Try This
here i perform addition of no and concatenation of string
private void button1_Click(object sender, EventArgs e)
{
bool chk,chk1;
int chkq;
chk = int.TryParse(textBox1.Text, out chkq);
chk1 = int.TryParse(textBox2.Text, out chkq);
if (chk1 && chk)
{
double a = Convert.ToDouble(textBox1.Text);
double b = Convert.ToDouble(textBox2.Text);
double c = a + b;
textBox3.Text = Convert.ToString(c);
}
else
{
string f, d,s;
f = textBox1.Text;
d = textBox2.Text;
s = f + d;
textBox3.Text = s;
}
}
int.TryPasrse() Methode is the best way so if the value was string you will never have an exception , instead of the TryParse Methode return to you bool value so you will know if the parse operation succeeded or failed
string yourText = "2";
int num;
bool res = int.TryParse(yourText, out num);
if (res == true)
{
// the operation succeeded and you got the number in num parameter
}
else
{
// the operation failed
}
string str = "123";
int i = Int.Parse(str);
If str is a valid integer string then it will be converted to integer and stored in i other wise Exception occur.