C# Program Crashes When No Number In TextBox - c#

I have a WPF Application in C# and for one of my textboxes, the input is taken and then automatically converted(Celsius to Fahrenheit). When you input a number, it works fine, but then once all the digits of the inputted number are removed, the program crashes. I guess this is because the input format is 'invalid' because it's just trying to convert nothing?
I'm stumped on how to work around this, any help would be appreciated, thanks!
This is my code within the application:
private void tempC_TextChanged(object sender, TextChangedEventArgs e)
{
tempC.MaxLength = 3;
Temperature T = new Temperature(celsius);
T.temperatureValueInCelcius = Convert.ToDecimal(tempC.Text);
celsius = Convert.ToDecimal(tempC.Text);
T.ConvertToFarenheit(celsius);
tempF.Text = Convert.ToString(T.temperatureValueInFahrenheit);
}
and this is the code from the API I have created:
public decimal ConvertToFarenheit(decimal celcius)
{
temperatureValueInFahrenheit = (celcius * 9 / 5 + 32);
return temperatureValueInFahrenheit;
}

You should call the method Decimal.TryParse that tries to convert the value and signal if the conversion is not possible.
if(Decimal.TryParse(tempC.Text, out celsius))
{
// Value converted correctly
// Now you can use the variable celsius
}
else
MessageBox.Show("The textbox cannot be converted to a decimal");

private void tempC_TextChanged(object sender, TextChangedEventArgs e)
{
Decimal temp;
if (!Decimal.TryParse(out temp, tempC.Text))
return;
...

Try this :
private void tempC_TextChanged(object sender, TextChangedEventArgs e)
{
if(tempC.Text = "")
return;
tempC.MaxLength = 3;
Temperature T = new Temperature(celsius);
T.temperatureValueInCelcius = Convert.ToDecimal(tempC.Text);
celsius = Convert.ToDecimal(tempC.Text);
T.ConvertToFarenheit(celsius);
tempF.Text = Convert.ToString(T.temperatureValueInFahrenheit);
}

Try Decimal.TryParse
Here is some examples
string value;
decimal number;
// Parse a floating-point value with a thousands separator.
value = "1,643.57";
if (Decimal.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// Parse a floating-point value with a currency symbol and a
// thousands separator.
value = "$1,643.57";
if (Decimal.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// Parse value in exponential notation.
value = "-1.643e6";
if (Decimal.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// Parse a negative integer value.
value = "-1689346178821";
if (Decimal.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// The example displays the following output to the console:
// 1643.57
// Unable to parse '$1,643.57'.
// Unable to parse '-1.643e6'.
// -1689346178821

Related

How to convert to two decimal places

How I can get the value that the user inputs to round to two decimal places. I tried to use.ToString("N2") but it gave me an error of {cannot convert string to System.IFormatProvider}. I can't seem to find a solution to this error.
code is here:
using System;
using System.Text.RegularExpressions;
namespace _selfTest
{
class Program
{
public static void Main(string[] args)
{
const string formula = #"^\d+\.?\d+?\%$";
percentages(formula, Console.ReadLine());
}
public static void percentages(string bottle, string flower)
{
Regex newRegular = new Regex(bottle);
bool input = newRegular.IsMatch(flower);
if (input)
Console.WriteLine("This Percentage Is Correct! " + bottle);
else
Console.WriteLine("This Percentage Is Incorrect... " + bottle);
Console.ReadLine();
}
}
}
You could use Decimal.TryParse method. And then you can use standard numeric format string "N2"
string consoleInput = Console.ReadLine();
if(Decimal.TryParse(consoleInput, out decimal parsedInput))
{
string resultString = parsedInput.ToString("N2");
}
else
{
// handling bad input
}
Your solution is just 2 steps away
Parsing the user input to decimal format
Then rounding off to 2 decimal places
.cs
static void Main(string[] args)
{
//Parse User input
var inputValue = Console.ReadLine();
inputValue = inputValue.Split('%')[0]; //To handle the trailing % sign
decimal outputValue;
var style = NumberStyles.Any;
var culture = CultureInfo.InvariantCulture;
if (Decimal.TryParse(inputValue, style, culture, out outputValue))
Console.WriteLine("Converted '{0}' to {1}.", inputValue, outputValue);
else
Console.WriteLine("Unable to convert '{0}'.", inputValue);
//Rounding off 2 decimal places
var roundedValue = Math.Round(outputValue, 2);
Console.WriteLine(roundedValue);
Console.Read();
}
Note
If you know ahead of time what culture you expect your inputs to be in you can specify that using culture info
var culture = new CultureInfo("en-US");// or ("fr-FR")

convert string from database to double

In my program I am using a database containing a Time (string previousTimeVASN).
I have a timer to clock total seconds. i would like to display the sum of previousTimeVASN + the total seconds.
I have error showing:
"System.FormatException: 'Input string was not in a correct format.'" at line: double test1 = Convert.ToDouble(previousTimeVASN);
any suggestion are much appreicated.
private void sNbtn_Click(object sender, RoutedEventArgs e)
{
TabControl.SelectedIndex = 1;
dtVASN.Tick += new EventHandler(dtVASN_Tick);
dtVASN.Interval = new TimeSpan(0, 0, 0, 0, 1);
}
void dtVASN_Tick(object sender, EventArgs e)
{
if (swVASN.IsRunning)
{
TimeSpan tsVASN = swVASN.Elapsed;
double test = tsVASN.TotalSeconds;
double test1 = Convert.ToDouble(previousTimeVASN);
txtVASN.Text = (test + test1).ToString();
}
}
The method Convert.ToDouble will throw FormatException if value is not a number in a valid format. You are getting the same here means either the value in previousTimeVASN is not a number or it is not in the expected format. Here is an alternate option for you to check whether the conversion is possible or not, that is, Double.TryParse Method
Converts the string representation of a number in a specified style
and culture-specific format to its double-precision floating-point
number equivalent. A return value indicates whether the conversion
succeeded or failed.
So the code can be revamped as like the following:
if (swVASN.IsRunning)
{
TimeSpan tsVASN = swVASN.Elapsed;
double test = tsVASN.TotalSeconds;
double test1;
Double.TryParse(previousTimeVASN, out test1);
txtVASN.Text = (test + test1).ToString();
}
if you want to alert the user that the second number is not valid then you can use the return value of parse like the following:
if(Double.TryParse(previousTimeVASN, out test1))
txtVASN.Text = (test + test1).ToString();
else
txtVASN.Text = "previous Time VASN is not valid:'

Simple addition string to int with 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();

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());
}

Categories

Resources