Operations only with textbox c# - 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();
}

Related

C# How to disable button when the value is zero

I'm a beginner to C# programming and I really need some help :)
I made 2 buttons that will increment or decrement the value in the text box which is initially zero.
private void bminus_Click(object sender, EventArgs e)
{
NUMBER--;
textBox2.Text = NUMBER.ToString();
}
private void bplus_Click(object sender, EventArgs e)
{
NUMBER++;
textBox2.Text = NUMBER.ToString();
}
Will there be a way that the decrement button will be disabled if the value is 0 so that there won't be negative numbers? Thank you, I'd really appreciate anyone's help! :)
private void bminus_Click(object sender, EventArgs e)
{
NUMBER--;
textBox2.Text = NUMBER.ToString();
if(NUMBER == 0){
bminus.Enabled = false;
}
}
private void bplus_Click(object sender, EventArgs e)
{
NUMBER++;
textBox2.Text = NUMBER.ToString();
bminus.Enabled = true;
}
That should do.
You can just directly insert logical state NUMBER not being 0 to your textBox2 Enabled property:
textBox2.Enabled = NUMBER != 0;
Or make a separate function from this:
private bool IsNotZero(double n)
{
return n != 0;
}
then:
textBox2.Enabled = IsNotZero(NUMBER);
All you need to do is add the following to the textBox2.TextChanged event handler and it should work with your current code.
private void textBox2_TextChanged(object sender, EventArgs e)
{
int output;
if (int.TryParse(textBox2.Text, out output))
{
bminus.Enabled = int.Parse(textBox2.Text) > 0;
}
}
NOTE: No one here has specified checking for an integer so I added int.TryParse and int.Parse for this purpose.
Button have a property named Enabled which you can set to true or false based on your logic.
Check the value using if condition. If the value is null or zero you can use button.enabled = false; code.if(value == zero || value == null) { button.enabled=false;} else {button.enabled = true;}

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

How to prevent crashing from a invalid input in C#

I made a simple application to add 2 numbers together but when I add two letters together or a invalid sign it crashes the program. How do I create a message box showing something saying "please put in a number" when someone inserts a letter
Here's my code:
public partial class frmAdd : Form
{
string first;
string second;
public frmAdd()
{
InitializeComponent();
}
private void btnFirst_Click(object sender, EventArgs e)
{
first = txtNumber.Text;
}
private void btnSecond_Click(object sender, EventArgs e)
{
second = txtNumber.Text;
}
private void btnResult_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(first);
int b = Convert.ToInt32(second);
int c = a + b;
txtResult.Text = c.ToString();
}
}
Use TryParse instead:
private void btnResult_Click(object sender, EventArgs e)
{
int a, b;
if (int.TryParse(first, out a) && int.TryParse(second, out b))
{
int c = a + b;
txtResult.Text = c.ToString();
}
else
{
MessageBox.Show("Invalid Input!");
}
}
Or perhaps a better method would be to trap the error when the user first inputs the data:
public partial class frmAdd : Form
{
int first; // changed to int
int second;
private void btnFirst_Click(object sender, EventArgs e)
{
if (!int.TryParse(txtNumber.Text, out this.first))
{
MessageBox.Show("Invalid Input!");
}
}
private void btnSecond_Click(object sender, EventArgs e)
{
if (!int.TryParse(txtNumber.Text, out this.second))
{
MessageBox.Show("Invalid Input!");
}
}
private void btnResult_Click(object sender, EventArgs e)
{
int c = first + second;
txtResult.Text = c.ToString();
}
}
You can use NumericUpDown control instead of TextBox - it will not allow user to input invalid data.
Or you can add validation to TextBox value after user entered something. Add ErrorProvider to your form. And subscribe to Validating event of txtNumber textbox. This event will occur when textbox loses focus. If entered text is not an integer, then error will be shown near texbox, and your button will not be clicked:
private void txtNumber_Validating(object sender, CancelEventArgs e)
{
int value;
if (!Int32.TryParse(txtNumber.Text, out value))
{
errorProvider1.SetError(txtNumber, "Value is not an integer");
return;
}
errorProvider1.SetError(txtNumber, "");
first = value; // it's better to save integer value than text
}
Validation looks like:
You can add a bit of validation to check if you can create an int from the string value passed in.
int.TryParse is a simple way of doing this.
And for the MessageBox you can just use the MessageBox calss
Example:
private void btnResult_Click(object sender, EventArgs e)
{
int a = 0;
int b = 0;
if (!int.TryParse(first, out a))
{
MessageBox.Show("first is not a number");
return;
}
if (!int.TryParse(second, out b))
{
MessageBox.Show("second is not a number");
return;
}
int c = a + b;
txtResult.Text = c.ToString();
}
Instead of using Convert.ToInt32(string), you might actually use Int32.tryParse(String, out int), as shown below:
int a, b;
a = Int32.tryParse(first, out a);
b = Int32.tryParse(second, out b);
If the conversion fails, the tryParse method will result in a zero. If it succeeds, it will give you the number which is to be found in the string.
Hope it helped you out, had to find this too in my first few days of C#.

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)

ArgumentOutOfRangeException and updateControls method

I am just a student begining to study C#, so I apologize if my questions are not very clear. I am stuck for the answer. I don't know how to code the ArgumentOutofRangeException, so the user doesn't go beyond the edges of the Lists. I have 2 of them, with two index variables. I also have a problem with updateControls. Any help would be greatly appreciated.
private void updateControls()
{
pictureBox1.Image = resList[currentResIndex].Photo;
lblName.Text = resList[currentResIndex].Title;
lblCity.Text = resList[currentResIndex].City;
lblPrice.Text = resList[currentResIndex].Price.ToString("C");
pictureBox1.Image = comList[currentCommIndex].Photo;
lblName.Text = comList[currentCommIndex].Title;
lblCity.Text = comList[currentCommIndex].City;
lblPrice.Text = comList[currentCommIndex].Price.ToString("C");
}
private void btnNext_Click(object sender, EventArgs e)
{
if (cboType.SelectedItem.ToString() == "Residential") //if they chose residential then increment resIndex
currentResIndex++;
updateControls();
else
currentCommIndex++;//or else commIndex
updateControls();
}
if (cboType.SelectedItem.ToString() == "Residential"
&& currentResIndex < resList.Count -1) // add this condition
currentResIndex++;
updateControls();
You could just enforce the range in your btnNext_Click method:
private void btnNext_Click(object sender, EventArgs e)
{
if (cboType.SelectedItem.ToString() == "Residential")//if they chose residential then increment resIndex
currentResIndex++;
else
currentCommIndex++;//or else commIndex
currentCommIndex = Math.Min(comList.Length-1, currentCommIndex);
currentResIndex = Math.Min(resList.Length-1, currentResIndex);
updateControls();
}
try
{
if (cboType.SelectedItem.ToString() == "Residential") //if they chose residential then increment resIndex
{
currentResIndex++;
}
else
{
currentCommIndex++;//or else commIndex
}
updateControls();
}
catch (ArgumentOutOfRangeException ex)
{
//Do the things you want when this exception occurs
}
But imho you shouldn't be using this. You should check whether or not the end of the List is reached.

Categories

Resources