Simple addition string to int with C# - c#

I have knowledge in PHP and I want to learn C # language but I do not even do simple addition.
I want to get the value of a ComboBox, convert this value to int and be able to add another value
Despite the conversion done, I have an error : Can not convert type "int" to "string.
My code :
private void btnValidate_click(object sender, RoutedEventArgs e)
{
int number = Test();
}
int Test()
{
string day = DayBirth.Text;
int number;
bool isNumeric = int.TryParse(day, out number);
if (isNumeric == false)
{
Resultat1.Text = "This is not a number";
}
else
{
Resultat1.Text = number + 10;
}
return number;
}
Thank you

The issue is that Resultat1.Text is expecting a string, not an int. You can do
Resultat1.Text = (number+10).ToString();
and it should work.

what you need to do is Converting your number to string after addition
Resultat1.Text = (number + 10).ToString;

Text property accept string value not integer so after addition you have to convert it as string
Resultat1.Text = (number + 10).ToString();

Related

c# check for integers in a textbox

I am trying to check if a textbox contains a number. The problem is that it always returns that it contains a non-numeric character.
I've tried several ways, but none of them seems to work.
One of the ways I've tried is:
if( Regex.IsMatch(tb.Text.Trim(), #"^[0-9]+$")) // tb.Text is the textbox
It does not matter what I enter in the textbox, it always returns that it contains a non-numeric character (I tried entering 1-9, 'a', 'b')
You could just parse the string to a specific number type, i.e.
double result;
if (!double.TryParse(tb.Text, out result))
{
//text is not a valid double;
throw new Exception("not a valid number");
}
//else the value is within the result variable
From your regex it seems that you need only integer values, so you should use int.TryParse or long.TryParse instead.
Quick and dirty test program:
void Main()
{
TestParse("1");
TestParse("a");
TestParse("1234");
TestParse("1a");
}
void TestParse(string text)
{
int result;
if (int.TryParse(text, out result))
{
Console.WriteLine(text + " is a number");
}
else
{
Console.WriteLine(text + " is not a number");
}
}
Results:
1 is a number
a is not a number
1234 is a number
1a is not a number
You could replace your Regex for this:
if(Regex.IsMatch(tb.Text.Trim(), #"[0-9]"))
Or for this:
if(Regex.IsMatch(tb.Text.Trim(), #"\d"))
you can use TryParse:
int value;
bool IsNumber = int.TryParse(tb.Text.Trim(), out value);
if(IsNumber)
{
//its number
}
private void btnMove_Click(object sender, EventArgs e)
{
string check = txtCheck.Text;
string status = "";
for (int i = 0; i < check.Length; i++)
{
if (IsNumber(check[i]))
status+="The char at "+i+" is a number\n";
}
MessageBox.Show(status);
}
private bool IsNumber(char c)
{
return Char.IsNumber(c);
}

Remove number from a textbox

I have this number in textbox "84,8441546842904" how to convert in 84,8 or 84,84 on button click event?
If by this you mean you want to parse the value and round it to a certain number of decimal places:
double value = Math.Round(double.Parse(textbox.Text), 2);
will parse the text and round it to 2 decimal places. You may need to use a System.Globalization.CultureInfo object when parsing to account for your local culture's number formatting.
See http://msdn.microsoft.com/en-us/library/75ks3aby.aspx
It almost looks like you are trying to trim the number to 1 or 2 precision (isn't the ',' used in some countries as the US '.'?). If this is what you're after, you can use Double.Parse to convert it to a Double and then look into the string format options described here to format it back to the textbox.
I use this kind of functions to validate user input.
This approach to the problem also respects user culture number format!
namespace Your_App_Namespace
{
public static class Globals
{
public static double safeval = 0; // variable to save former value!
public static bool isPositiveNumeric(string strval, System.Globalization.NumberStyles NumberStyle)
// checking if string strval contains positive number in USER CULTURE NUMBER FORMAT!
{
double result;
boolean test;
if (strval.Contains("-")) test = false;
else test = Double.TryParse(strval, NumberStyle, System.Globalization.CultureInfo.CurrentCulture, out result);
// if (test == false) MessageBox.Show("Not positive number!");
return test;
}
public static string numstr2string(string strval, string nofdec)
// conversion from numeric string into string in USER CULTURE NUMBER FORMAT!
// call example numstr2string("12.3456", "0.00") returns "12.34"
{
string retstr = 0.ToString(nofdec);
if (Globals.isPositiveNumeric(strval, System.Globalization.NumberStyles.Number)) retstr = double.Parse(strval).ToString(nofdec);
else retstr = Globals.safeval.ToString(nofdec);
return retstr;
}
public static string number2string(double numval, string nofdec)
// conversion from numeric value into string in USER CULTURE NUMBER FORMAT!
// call example number2string(12.3456, "0.00") returns "12.34"
{
string retstr = 0.ToString(nofdec);
if (Globals.isPositiveNumeric(numval.ToString(), System.Globalization.NumberStyles.Number)) retstr = numval.ToString(nofdec);
else retstr = Globals.safeval.ToString(nofdec);
return retstr;
}
}
// Other Your_App_Namespace content
}
// This is the way how to use those functions
// function to call when TextBox GotFocus
private void textbox_clear(object sender, System.Windows.RoutedEventArgs e)
{
TextBox txtbox = e.OriginalSource as TextBox;
// save original value
Globals.safeval = double.Parse(txtbox.Text);
txtbox.Text = "";
}
// function to call when TextBox LostFocus
private void textbox_change(object sender, System.Windows.RoutedEventArgs e)
{
TextBox txtbox = e.OriginalSource as TextBox;
// text from textbox into sting with checking and string format
txtbox.Text = Globals.numstr2string(txtbox.Text, "0.00");
}
double i = 0;
if (double.TryParse(tbxNumber.Text,out i)) {
MessageBox.Show("number is " + i.ToString());
}

Add numbers in c#

i have a numerical textbox which I need to add it's value to another number
I have tried this code
String add = (mytextbox.Text + 2)
but it add the number two as another character like if the value of my text box is 13 the result will become 132
The type of mytextbox.Text is string. You need to parse it as a number in order to perform integer arithmetic, e.g.
int parsed = int.Parse(mytextbox.Text);
int result = parsed + 2;
string add = result.ToString(); // If you really need to...
Note that you may wish to use int.TryParse in order to handle the situation where the contents of the text box is not an integer, without having to catch an exception. For example:
int parsed;
if (int.TryParse(mytextbox.Text, out parsed))
{
int result = parsed + 2;
string add = result.ToString();
// Use add here
}
else
{
// Indicate failure to the user; prompt them to enter an integer.
}
String add = (Convert.ToInt32(mytextbox.Text) + 2).ToString();
You need to convert the text to an integer to do the calculation.
const int addend = 2;
string myTextBoxText = mytextbox.Text;
var doubleArray = new double[myTextBoxText.ToCharArray().Length];
for (int index = 0; index < myTextBoxText.ToCharArray().Length; index++)
{
doubleArray[index] =
Char.GetNumericValue(myTextBoxText.ToCharArray()[index])
* (Math.Pow(10, (myTextBoxText.ToCharArray().Length - 1) - index));
}
string add =
(doubleArray.Aggregate((term1, term2) => term1 + term2) + addend).ToString();
string add=(int.Parse(mytextbox.Text) + 2).ToString()
if you want to make sure the conversion doesn't throw any exception
int textValue = 0;
int.TryParse(TextBox.text, out textValue);
String add = (textValue + 2).ToString();
int intValue = 0;
if(int.TryParse(mytextbox.Text, out intValue))
{
String add = (intValue + 2).ToString();
}
I prefer TryPase, then you know the fallback is going to be zero (or whatever you have defined as the default for intValue)
You can use the int.Parse method to parse the text content into an integer:
String add = (int.Parse(mytextbox.Text) + 2).ToString();
Others have posted the most common answers, but just to give you an alternative, you could use a property to retrieve the integer value of the TextBox.
This might be a good approach if you need to reuse the integer several times:
private int MyTextBoxInt
{
get
{
return Int32.Parse(mytextbox.Text);
}
}
And then you can use the property like this:
int result = this.MyTextBoxInt + 2;

How can I check if a string is a number?

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
and so on...
Is there a specific function?
Look up double.TryParse() if you're talking about numbers like 1, -2 and 3.14159. Some others are suggesting int.TryParse(), but that will fail on decimals.
string candidate = "3.14159";
if (double.TryParse(candidate, out var parsedNumber))
{
// parsedNumber is a valid number!
}
EDIT: As Lukasz points out below, we should be mindful of the thread culture when parsing numbers with a decimal separator, i.e. do this to be safe:
double.TryParse(candidate, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var parsedNumber)
If you just want to check if a string is all digits (without being within a particular number range) you can use:
string test = "123";
bool allDigits = test.All(char.IsDigit);
Yes there is
int temp;
int.TryParse("141241", out temp) = true
int.TryParse("232a23", out temp) = false
int.TryParse("12412a", out temp) = false
Hope this helps.
Use Int32.TryParse()
int num;
bool isNum = Int32.TryParse("[string to test]", out num);
if (isNum)
{
//Is a Number
}
else
{
//Not a number
}
MSDN Reference
Use int.TryParse():
string input = "141241";
int ouput;
bool result = int.TryParse(input, out output);
result will be true if it was.
Yep - you can use the Visual Basic one in C#.It's all .NET; the VB functions IsNumeric, IsDate, etc are actually static methods of the Information class. So here's your code:
using Microsoft.VisualBasic;
...
Information.IsNumeric( object );
int value;
if (int.TryParse("your string", out value))
{
Console.WriteLine(value);
}
This is my personal favorite
private static bool IsItOnlyNumbers(string searchString)
{
return !String.IsNullOrEmpty(searchString) && searchString.All(char.IsDigit);
}
Perhaps you're looking for the int.TryParse function.
http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx
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
int result = 0;
bool isValidInt = int.TryParse("1234", out result);
//isValidInt should be true
//result is the integer 1234
Of course, you can check against other number types, like decimal or double.
You should use the TryParse method for the int
string text1 = "x";
int num1;
bool res = int.TryParse(text1, out num1);
if (res == false)
{
// String is not a number.
}
If you want to validate if each character is a digit and also return the character that is not a digit as part of the error message validation, then you can loop through each char.
string num = "123x";
foreach (char c in num.ToArray())
{
if (!Char.IsDigit(c))
{
Console.WriteLine("character " + c + " is not a number");
return;
}
}
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.
Starting with C# 7.0, you can declare the out variable in the argument
list of the method call, rather than in a separate variable
declaration. This produces more compact, readable code, and also
prevents you from inadvertently assigning a value to the variable
before the method call.
bool isDouble = double.TryParse(yourString, out double result);
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier
You could use something like the following code:
string numbers = "numbers you want to check";
Regex regex = new Regex("^[0-9]+$"));
if (regex.IsMatch(numbers))
{
//string value is a number
}
public static void Main()
{
string id = "141241";
string id1 = "232a23";
string id2 = "12412a";
validation( id, id1, id2);
}
public static void validation(params object[] list)
{
string s = "";
int result;
string _Msg = "";
for (int i = 0; i < list.Length; i++)
{
s = (list[i].ToString());
if (string.IsNullOrEmpty(s))
{
_Msg = "Please Enter the value";
}
if (int.TryParse(s, out result))
{
_Msg = "Enter " + s.ToString() + ", value is Integer";
}
else
{
_Msg = "This is not Integer value ";
}
}
}
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;
}
}
I'm not a programmer of particularly high skills, but when I needed to solve this, I chose what is probably a very non-elegant solution, but it suits my needs.
private bool IsValidNumber(string _checkString, string _checkType)
{
float _checkF;
int _checkI;
bool _result = false;
switch (_checkType)
{
case "int":
_result = int.TryParse(_checkString, out _checkI);
break;
case "float":
_result = Single.TryParse(_checkString, out _checkF);
break;
}
return _result;
}
I simply call this with something like:
if (IsValidNumber("1.2", "float")) etc...
It means that I can get a simple true/false answer back during If... Then comparisons, and that was the important factor for me. If I need to check for other types, then I add a variable, and a case statement as required.
use this
double num;
string candidate = "1";
if (double.TryParse(candidate, out num))
{
// It's a number!
}
int num;
bool isNumeric = int.TryParse("123", out num);
namespace Exception
{
class Program
{
static void Main(string[] args)
{
bool isNumeric;
int n;
do
{
Console.Write("Enter a number:");
isNumeric = int.TryParse(Console.ReadLine(), out n);
} while (isNumeric == false);
Console.WriteLine("Thanks for entering number" + n);
Console.Read();
}
}
}
Regex.IsMatch(stringToBeChecked, #"^\d+$")
Regex.IsMatch("141241", #"^\d+$") // True
Regex.IsMatch("232a23", #"^\d+$") // False
Regex.IsMatch("12412a", #"^\d+$") // False
The problem with some of the suggested solutions is that they don't take into account various float number formats. The following function does it:
public bool IsNumber(String value)
{
double d;
if (string.IsNullOrWhiteSpace(value))
return false;
else
return double.TryParse(value.Trim(), System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out d);
}
It assumes that the various float number styles such es decimal point (English) and decima comma (German) are all allowed. If that is not the case, change the number styles paramater. Note that Any does not include hex mumbers, because the type double does not support it.

Convert string to integer

I need help with my code. I would like to write only numbers/integers in my textbox and would like to display that in my listbox.
Is my code below in order? This seems to give an error.
int yourInteger;
string newItem;
newItem = textBox1.Text.Trim();
if (newItem == Convert.ToInt32(textBox1.Text))
{
listBox1.Items.Add(newItem);
}
====
Update:
This is how my code looks like now. My question is, can listBox handle the data type "long"? Because when I entered the number 20,000,000 I just got an hour glass for 20 minutes. But when I tried this one with the console, I got the answer. So I'm not sure what kind of element can handle data type "long".
string newItem;
newItem = textBox1.Text.Trim();
Int64 num = 0;
if(Int64.TryParse(textBox1.Text, out num))
{
for (long i = 2; i <= num; i++)
{
//Controls if i is prime or not
if ((i % 2 != 0) || (i == 2))
{
listBox1.Items.Add(i.ToString());
}
}
}
private void btnClear_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
}
int result = int.Parse(textBox1.Text.Trim());
If you want to check for validity:
int result;
if (int.TryParse(textBox1.Text.Trim(), out result)) // it's valid integer...
// int is stored in `result` variable.
else
// not a valid integer
Use this:
int yourInteger;
string newItem;
newItem = textBox1.Text.Trim();
Int32 num = 0;
if ( Int32.TryParse(textBox1.Text, out num))
{
listBox1.Items.Add(newItem);
}
else
{
customValidator.IsValid = false;
customValidator.Text = "You have not specified a correct number";
}
This assumes you have a customValidator.
Use int.TryParse() to check if string contains integer value.
textBox1.Text may not contain a valid string representation of an integer (or is just an empty string). To work around that, use Int32.TryParse().
You can do:
Convert.ToInt32(input);
For a longer function using this you can look at:
http://msdn.microsoft.com/en-us/library/bb397679.aspx
Basically it checks if the string is null, then it will call int.Parse. This will work under WindowsCE also, which doesn't have int.TryParse.
To be specific as to why your code fails to compile it is because you are comparing a string (newItem) against the result of Convert.ToInt32, which is an integer, which it wont let you do. Also Convert.ToInt32 will raise an exception it the string passed in is not a number.
You can try using int.TryParse, or alternatively write a simple regular expression to validate your input:
int i;
bool isInteger = int.TryParse(textBox1.Text,out i);
or
bool isInteger = System.Text.RegularExpressions.Regex.IsMatch("^\d+$", textBox1.Text);
Are you checking for an empty string?
int yourInteger;
string newItem;
newItem = textBox1.Text.Trim();
if(newItem != string.Empty)
{
if ( newItem == Convert.ToInt32(textBox1.Text))
{
listBox1.Items.Add(newItem);
}
}

Categories

Resources