Input string was not in the correct form - c#

a C# beginner here. I've been following a guide on making a simple calculator. Everything worked fine 'till I added the point button. If I use the calculator to calculate basic integers there's no problem. However, when I add in the point button to calculate doubles with a decimal it gets all screwed up. Any ideas?
// Above this are the numeric buttons, no problem with those
private void btnPoint_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnPoint.Text;
}
double total1 = 0;
double total2 = 0;
private void btnPlus_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text); // Error comes here
txtDisplay.Clear();
}
private void btnEquals_Click(object sender, EventArgs e)
{
total2 = total1 + double.Parse(txtDisplay.Text); // And one time it came here
txtDisplay.Text = total2.ToString();
total1 = 0;
}

Time ago I've made a simple calculator and for checking the input I have used regex(if you don't know what is a Regex take a look here
You can use this regex for checking the input: ^[0-9]{0,}([.,][0-9]{1,})?$
It allows:
0
10
100
1,2
1.2
But not
.1
,1
And all type of string
For using the regex in c# you must declare a Regex object. Before that you need to add using System.Text.RegularExpressions;
Than use the regex is quite simple
Regex regex=new Regex(pattern);
if(regex.IsMatch(myTextBox.Text))
{//Do something
}
else{//Catch the error
}
If you want know more about regular expression take a look here

Instead of using Double.Parse use Double.TryParse.
private void btnPlus_Click(object sender, EventArgs e)
{
Double v = 0;
if ( Double.TryParse(txtDisplay.Text.Trim(), out v)
{
total1 = total1 + v;
txtDisplay.Clear();
}
else
{
// Invalid value
}
}

Related

Operations only with textbox c#

I'm trying to make a simple calculator using only textbox.
I Thought my code was correct, but the result is almost always wrong.
This is the code:
void TextBoxPercorsoTextChanged(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty(textBoxPercorso.Text) && !string.IsNullOrEmpty(textBoxAgilitySmallVelocita.Text))
textBoxAgilitySmallTps.Text=(Convert.ToDecimal(textBoxPercorso.Text)/Convert.ToDecimal(textBoxAgilitySmallVelocita.Text)).ToString();
}
void TextBoxAgilitySmallVelocitaTextChanged(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty(textBoxPercorso.Text) && !string.IsNullOrEmpty(textBoxAgilitySmallVelocita.Text))
textBoxAgilitySmallTps.Text=(Convert.ToDecimal(textBoxPercorso.Text)/Convert.ToDecimal(textBoxAgilitySmallVelocita.Text)).ToString();
}
I have tried to do some attempts. For example I tried to do 10/5, but the result is 0.5. Only with 10/10 the result is correct.
Can you help me, please?
Try avoiding magic button antipattern (extract a method); do not repeat youself (copy + paste):
private void ComputeSmallTps() {
decimal perCorso;
decimal smallVelocita;
// first, parse arguments...
if (!decimal.TryParse(textBoxPercorso.Text, out perCorso) ||
!decimal.TryParse(textBoxAgilitySmallVelocita.Text, out smallVelocita)) {
// invalid input data, e.g. "bla-bla-bla"
textBoxAgilitySmallTps.Text = "???";
return;
}
try {
// ...then compute: put the right formula here
// put break point here, check smallVelocita and perCorso values
decimal result = smallVelocita / perCorso;
textBoxAgilitySmallTps.Text = result.ToString();
}
catch (ArithmeticException) {
// Division by zero, overflow
textBoxAgilitySmallTps.Text = "???";
}
}
...
void TextBoxPercorsoTextChanged(object sender, EventArgs e) {
// Just a simple call, no complex logic here
ComputeSmallTps();
}
void TextBoxAgilitySmallVelocitaTextChanged(object sender, EventArgs e) {
ComputeSmallTps();
}

Fill a textbox based on another textbox text

I have TextBoxA and TextBoxB. What i want to do is , whenever i put a number (yes, both of the textboxes values are always integers) in TextBoxA , TextBoxB should "autocomplete" with value (100-TextBoxA). Same thing goes for TextBoxB. The sum of TextBoxA and TextBoxB should always be 100.
Here's what i've already tried:
static void TextBoxA_TextChanged()...
{
int a = Convert.ToInt32(TextBoxA.Text);
int b = Convert.ToInt32(TextBoxB.Text);
string text = (100-a).ToString();
TextBoxB.Text = text;
}
Static void TextBoxB_TextChanged()...
{
int a = Convert.ToInt32(TextBoxA.Text);
int b = Convert.ToInt32(TextBoxB.Text);
string text = (100-b).ToString();
TextBoxA.Text = text;
}
But it doesn't work.
Here's what you can try:
private void TextBoxA_TextChanged(object sender, EventArgs e)
{
int num = 0;
if (int.TryParse(TextBoxA.Text, out num))
{
string text = (100 - num).ToString();
TextBoxB.Text = text;
}
}
private void TextBoxB_TextChanged(object sender, EventArgs e)
{
int num = 0;
if (int.TryParse(TextBoxB.Text, out num))
{
string text = (100 - num).ToString();
TextBoxA.Text = text;
}
}
This will autocomplete on either TextBox on TextChanged Event.
First, i dont know why your event handlers are declared static.. its usually got to be :
private void TextBoxA_TextChanged(object sender, EventArgs e) { }
Secondly, you know if you have 2 textboxs, and each one triggers the other, you'll never go out of the TextChanged event.
To understand me more, here's an example :
1- You set TextBoxB.text = "1";2- TextBoxB.TextChanged triggers, it
sets TextBoxA.Text = "2"; 3- TextBoxA.TextChanged triggers, it sets
TextBoxB.Text = "1";
And it continues like this until i believe you'll get an Exception of memory.
EDIT : The opertator '-' works on numbers. You can't substract a number from a string. they have to be both numbers, so convert them first.
EDIT 2 :
Here's a code i wrote that works fine
private void textBox1_TextChanged(object sender, EventArgs e)
{
int n;
if (int.TryParse(textBox1.Text, out n)) // Check if the text value is a number
{
if (n > 100) // Since you want a sum of 100
return;
int m = 100 - n; // remaining
if (textBox2.Text != m.ToString()) // to not re-trigger the TextChanged event
textBox2.Text = m.ToString();
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
int n;
if (int.TryParse(textBox2.Text, out n)) // Check if the text value is a number
{
if (n > 100) // Since you want a sum of 100
return;
int m = 100 - n; // remaining
if (textBox1.Text != m.ToString()) // to not re-trigger the TextChanged event
textBox1.Text = m.ToString();
}
}
Try this. This is a more efficient and elegant way I'd choose using lambda expressions, without repeating the method:
private void onChangeDoSum(object sender, EventArgs e,
TextBox substractNumber, TextBox sumNumber)
{
sumNumber.Text = (100 - Int32.Parse(substractNumber.Text)).ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.TextChanged += (a, b) => onChangeDoSum(sender, e, textBox1, textBox2);
textBox2.TextChanged += (a, b) => onChangeDoSum(sender, e, textBox2, textBox1);
}
Alternatively use Int32.TryParse to prevent unexpected results.
I think you can do something like this
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Text = (100 - Int32.Parse(textBox1.Text)).ToString();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox1.Text = (100 - Int32.Parse(textBox2.Text)).ToString();
}
when I see that static word I think you have tried to create these method by yourself and you forgot to add
textBox1.TextChanged += textBox1_Changed;
// I saw other post where you wrote that it could raise exception and fall. Of course it can. You can use if condition like
textBox1.Text != null && textBox1.Text != ""
before value would be changed or TryParse() method

C# FormatException Unhandled

I'm working with Microsoft Visual C# 2010 Express. I am currently trying to get my calculator to do addition and subtraction but I keep getting this error? I am using switch statements throughout the calculator.
private void Add_Click(object sender, EventArgs e)
{
//Storing the number on display in variables total1 for further use
//Making addition happen before = is clicked
total1 = total1 + double.Parse(textDisplay.Text);
textDisplay.Text = textDisplay.Text + Add.Text;
theOperator = "+";
}
private void Subtract_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(textDisplay.Text);
textDisplay.Clear();
theOperator = "-";
}
private void Equals_Click(object sender, EventArgs e)
{
switch(theOperator)
{
case "+": //Addition
total1 = total1 + double.Parse(textDisplay.Text);---> error in this line
textDisplay.Text = result.ToString();
total1 = 0;
break;
case "-": //Subtraction
result = total1 - double.Parse(textDisplay.Text);--->error in this line
textDisplay.Text = result.ToString();
total1 = 0;
break;
On your problem lines, you have:
double.Parse(textDisplay.Text)
But in your Add_Click method you have this:
textDisplay.Text = textDisplay.Text + Add.Text;
I am hypothesizing that that your Add button label is not a number (likely it is either Add or +). So when you run the line above, you would get something like either:
1234Add
1234+
This will cause an exception in when you pass it to double.Parse because this function does not accept bad input (so unless textDisplay.Text is a number, it will give an error). You would want to use double.TryParse instead if you want to test for bad input.
Here is an example on how to test for bad input:
private void Equals_Click(object sender, EventArgs e)
{
// Remove the operator from the value we want to process.
// It is expected this will be at the end.
var userValue = textDisplay.Text;
if (userValue.EndsWith(theOperator))
{
userValue = userValue.Substring(0, userValue.Length - theOperator.Length).Trim();
}
// Test for valid input.
// Test our "userValue" variable which has the pending operator removed.
double value;
if (!double.TryParse(userValue, out value))
{
// Invalid input.
// Alert the user and then exit this method.
MessageBox.Show("A number was not entered.");
return;
}
// If we get here, the "value" variable is a valid number.
// Use it for calculations.
...
Edit
As a side note, you do have some logic issues with respect to how you are using and resetting result and total1 in your OP. I'm not going to do your homework for you, but it would be a good idea to review your usages of these variables.

use parentheses in c# calculator

Hello I just write a simple calculator in C# and I want to improve my program to handle parentheses.
Here is my button to add 1(digit):
private void btnOne_Click(object sender, EventArgs e)
{
txtResult.Text += '1';
}
This is a method for my Plus button:
private void btnPlus_Click(object sender, EventArgs e)
{
lblChar.Text = "+";
num1 = float.Parse(txtResult.Text);
txtResult.Text = "";
}
And this is for to calculate final result:
private void btnEqual_Click(object sender, EventArgs e)
{
num2 = float.Parse(txtResult.Text);
if (lblChar.Text == "+")
{
num3 = num1 + num2;
txtResult.Text = Convert.ToString(num3);
}
}
Anyone can help me to write parentheses for my program?
You can use NCalc - Mathematical Expressions Evaluator for .NET
Expression e = new Expression("2 + (3 + 5)*6");
var result = e.Evaluate();

Input string was not in a correct format and how to learn c#

I am new to c# , i have read few basic concepts and now want to learn actual programming , thats why i started out with simple Calculator program
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double num1 = 0;
double num2 = 0;
private void one_Click(object sender, EventArgs e)
{
textBox1.Text =textBox1.Text+one.Text;
}
private void clear_Click(object sender, EventArgs e)
{
textBox1.Clear();
// textBox1.Text = " ";
}
private void two_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text+two.Text;
}
private void three_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text+three.Text;
}
private void four_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text+four.Text;
}
private void five_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + five.Text;
}
private void six_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + six.Text;
}
private void seven_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + seven.Text;
}
private void eight_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + eight.Text;
}
private void nine_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + nine.Text;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void add_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(textBox1.Text) ;
textBox1.Clear();
}
private void ten_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + ten.Text;
}
private void equal_Click(object sender, EventArgs e)
{
num2 = num1 + double.Parse(textBox1.Text) ;
textBox1.Text = num2.ToString();
num1 = 0;
}
}
}
This code is given in the book and they said its working .Actual problem is it works ONLY some times and some times it gives error as " Input string was not in a correct format "
What is the solution .
My second question is -- is this right approach to learn any programming language ? or should i just continue reading some more stuff n programs ?
If some one can help me with websites containing sample programs it will be very helpful .
Your problem is parsing the double. The Parse function cannot parse a string that does not represent a double.
Consider the string "135.42", this could easily be parsed to the double value 135.42. But what if the string was "Abc#%%#". This does not represent a double value and that is where you are getting your exception.
If this is your first programming language, you should read a introductory book to C# as a new programmer.
If double.Parse can't parse the string into a double then an exception is thrown. However, it's often better to use double.TryParse as it will simply return false instead of throwing an exception.
double tmp;
if(double.TryParse(textBox1.Text, out tmp))
{
num2 = num1 + tmp;
textBox1.Text = num2.ToString();
num1 = 0;
}
else
{
//double could not be parsed from textbox
}
You need to restrict the user to input only numbers in your textbox. You can do it by using keydown event of textbox. Where you will check if inputed char was numeric, only then keep it in the textbox. Here is the solution of your problem. Have a look at this:
How do I make a textbox that only accepts numbers?
For learning C#, i would prefer:
C# 5.0 in a Nutshell: The Definitive Reference
Before you do double.Parse() you should verify the user input, i.e. That it is an actual number.
I would suggest using TryParse method instead, as such:
double num;
bool isNum = double.TryParse(Str, out num);
if (isNum)
{
//Calculate here
}
If you wanted to handle invalid arguments more gracefully you could use Double.TryParse instead.
Here is the magic: double.Parse(textBox1.Text)
This function accepts only numbers (with comma or dot depends on your culture) in the string. If you pass anything else you will receive the given exception. Validate the input before you parse it or Use TryParse
double valueinDouble;
var success = double.TryParse(textBox1.Text), out valueinDouble)
if (success)
{
// do the calculation here
}
The TryParse has another implementation where you can specify the culture.
var success = double.TryParse(textBox1.Text), NumberStyles.Any, new CultureInfo("en-US"), out valueinDouble)

Categories

Resources