Simple Calculator Application in C# - c#

I have two quick question about this simple calculator application I am trying to build in C#. (not homework by the way) I am trying to get the MessageBox.Show message to show in the multiply and add sections of my code, but they don't seem to be displaying even if I enter a negative value. The application just seems to do the math anyways. Also, this may be a dumb one, how do I get rid of the label5 text that appears in the application with out deleting it in the properties window?
Any help will be greatly appreciated, thanks!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AddMultiply
{
public partial class AddMultiply : Form
{
public AddMultiply()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void txtFirstValue_TextChanged(object sender, EventArgs e)
{
}
private void btnAdd_Click(object sender, EventArgs e)
{
double firstValue;
double secondValue;
double answer;
while (double.TryParse(txtFirstValue.Text, out firstValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
while(double.TryParse(txtSecondValue.Text, out secondValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
answer = firstValue + secondValue;
lblAnswer.Text = answer.ToString();
}
private void btnMultiply_Click(object sender, EventArgs e)
{
double firstValue;
double secondValue;
double answer;
while (double.TryParse(txtFirstValue.Text, out firstValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
while (double.TryParse(txtSecondValue.Text, out secondValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
answer = firstValue * secondValue;
lblAnswer.Text = answer.ToString();
}
private void lblAnswer_Click(object sender, EventArgs e)
{
lblAnswer.Text = ""; //tries to get rid of "label5" text in application, but fails to do so
}
}
}

1)you should change the while to "if":
private void btnAdd_Click(object sender, EventArgs e)
{
double firstValue;
double secondValue;
double answer;
if (double.TryParse(txtFirstValue.Text, out firstValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
if(double.TryParse(txtSecondValue.Text, out secondValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
answer = firstValue + secondValue;
lblAnswer.Text = answer.ToString();
}
2) where is Ladel5 ? It doesn't seem to be exist...

You can try the following code to show the MessageBox then the value is less than 0:
if (n1 < 0 || n2 < 0)
MessageBox.Show("Value less than ZERO ", "Value less than ZERO",MessageBoxButtons.OK , MessageBoxIcon.Exclamation);
As for getting rid of the label you can try :
label5.Visible = false;

Related

Is it necessary to use switch cases in each widget function of windows forms if we have different cases to consider?

I am making a simple Unit Converter windows form application in c#.net, as it is a unit converter, I added a drop-down list or combo box to select "mass", "length", "temperature", etc. To add functionality to those combo box items, do I have to use a switch case for that particular selection in each and every widget function(i.e. Calculate Button, Combo Box, Radio buttons, etc.) or is there a way to get this done at once? Below is the incomplete code I have written so far in the visual studio. I have used switch cases in Calculate Button and Combo Box Selector for now (marked with comments).
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UnitConverter
{
public partial class formUnitConverter : Form
{
public formUnitConverter()
{
InitializeComponent();
}
private void FormUnitConverter_Load(object sender, EventArgs e)
{
}
private void BtnCalculate_Click(object sender, EventArgs e) //Calculate Button
{
if (isNum(textBox1.Text))
{
switch (comboBox1.SelectedItem)
{
case "Mass":
{
if (radioButton1.Checked)
{
double res = Convert.ToDouble(textBox1.Text) * 2.20462262185;
textBox2.Text = Math.Round(res, 4).ToString();
}
if (radioButton2.Checked)
{
double res = Convert.ToDouble(textBox1.Text) / 2.20462262185;
textBox2.Text = Math.Round(res, 4).ToString();
}
break;
}
}
label5.Text = "";
}
else
{
label5.Text = "Plese enter numbers only.";
}
}
private void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if(radioButton1.Checked)
{
label3.Text = "kg";
label4.Text = "lbs";
textBox2.Text = "";
}
}
private void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
if (radioButton2.Checked)
{
label3.Text = "lbs";
label4.Text = "kg";
textBox2.Text = "";
}
}
public bool isNum(string s)
{
return double.TryParse(s, out double i);
}
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e) //Combo Box Selector
{
switch (comboBox1.SelectedItem)
{
case "Mass":
{
label3.Text = "kg";
label4.Text = "lbs";
break;
}
case "Temperature":
{
label3.Text = "F";
label4.Text = "C";
break;
}
}
}
}
}

Why is this code not displaying output on the textbox?

I am beginning with C#. When I run the following code and click the generate button the output does not appear in the textbox. Why is this? I am calling the function palendrome and its not updating the textbox. What am I doing wrong? Am I missing something? What do I need to fix. I don't see the error. Please help. :(
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PalendromeChecker
{
public partial class Form1 : Form
{
int num;
int count;
static int result;
int setPalendromeValue;
int copyCount;
public Form1()
{
InitializeComponent();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
count = Int32.Parse(textBox2.Text);
copyCount = count;
if (!int.TryParse(textBox2.Text, out count))
{
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
else if (count < 0 || count > 100)
{
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
}
public static int palendrome(int num)
{
int temp = num; ;
int r;
int rv = 0;
while (num > 0)
{
r = num % 10;
rv = rv * 10 + r;
num /= 10;
}
if (rv == temp)
{
result = temp;
return temp;
}
else
{
return 0;
}
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
while (copyCount != 0)
{
string resultInString = result.ToString();
textBox3.Text = resultInString;
textBox3.Visible = true;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
num = Int32.Parse(textBox1.Text);
//MessageBox.Show(this.textBox1.Text);
if (!int.TryParse(textBox1.Text, out num))
{
//MessageBox.Show("This is a number only field");
//return;
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
else if (num < 0 || num > 1000000000)
{
// MessageBox.Show("Invalid Input needs to be between 0 and 1,000,000,000");
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
label4.Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
int palendromeValue;
while (count != 0)
{
palendromeValue = palendrome(num);
count--;
}
}
}
}
It is not generating any input on the textbox because your function palendrome is not generating in anyway output on any of textbox1 to textbox3.
Try this:
textBox1.Text = "output"; //Whatever output you want.
If you want to show result in textBox3 the code to update it's text property should be inside button click handler, not in text changed handler.
Also while (count != 0) or while (copyCount != 0) are like infinite loops (almost). They are going to make your form unresponsive. You need to avoid those.

'Simple' Calculator - C# (Set focus on text box 2...)

To give you all a bit of my programming background, I'm a first year Software Engineering Student (started this academic year). I've been programming for the best part of a year, mainly using HTML and Python. The language I will be using throughout my degree is C#. (I'm still fairly new to this programming language) and the IDE being used is Visual Studio 2013.
As I've literally just started my course 3 weeks ago, I was given a task to do. It was to create a simple calculator which can add, subtract, multiply, divide various numbers from user input. This I have done, as well as implementing a way for users to do maths with floating points.
In order to make the calculator a bit more user friendly, I decided to add number buttons, based on the layout of the Windows Calculator. It has two input text boxes and one output text box which allows users to copy and then paste their answer into other documents etc. I've only got 4 operator buttons which are; +,-,*,/. In addition, I also added an 'Exit' button.
Whenever the user inputs the two values, they have to press one of the operator buttons. For example; if the user types in 10 in 'txtNum1' and 20 in 'txtNum2' and presses 'btnAdd', the value of the sum will be represented in 'txtAnswer'.
(I would provide an image of the form but I require at least 10 reputation points on this website, so apologies in advance)
The issues which I'm having with the form are;
- I can only input values into one text box (using the mouse + available buttons on screen). I've tried using boolean in order to check whether 'Focus' has been set to a particular box and then going from there but I'm completely lost on what to do next. My lecturer actually advised me to use this boolean method in order to help solve the issue.
Any advice is greatly appreciated + I would appreciate it if you guys taught me a better way of representing my code, maybe reduce the amount by using functions etc. I'm always keen to learn new tips + tricks.
Here's the source code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AddUpNums
{
public partial class Form1 : Form
{
Boolean ff;
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
private void checkForEmptySpace()
{
if (txtNum1.Text == "")
txtNum1.Text = "0";
if (txtNum2.Text == "")
txtNum2.Text = "0";
}
private void btnAddUp_Click(object sender, EventArgs e)
{
checkForEmptySpace();
double num1, num2, sum;
num1 = double.Parse(txtNum1.Text);
num2 = double.Parse(txtNum2.Text);
sum = num1 + num2;
txtAnswer.Text = Convert.ToString(sum);
}
private void btnSubtract_Click(object sender, EventArgs e)
{
checkForEmptySpace();
double num1, num2, sum;
num1 = double.Parse(txtNum1.Text);
num2 = double.Parse(txtNum2.Text);
sum = num1 - num2;
txtAnswer.Text = Convert.ToString(sum);
}
private void btnMultiply_Click(object sender, EventArgs e)
{
checkForEmptySpace();
double num1, num2, sum;
num1 = double.Parse(txtNum1.Text);
num2 = double.Parse(txtNum2.Text);
sum = num1 * num2;
txtAnswer.Text = Convert.ToString(sum);
}
private void btnDivide_Click(object sender, EventArgs e)
{
checkForEmptySpace();
double num1, num2, sum;
num1 = double.Parse(txtNum1.Text);
num2 = double.Parse(txtNum2.Text);
sum = num1 / num2;
txtAnswer.Text = Convert.ToString(sum);
}
private void btn0_Click(object sender, EventArgs e)
{
//txtNum2.Focus();
//if (txtNum2.Focus() == true)
// txtNum2.Text += "0";
//if (txtNum1.Focus() == true)
// txtNum1.Text += "0";
}
private void btn1_Click(object sender, EventArgs e)
{
txtNum1.Text += "1";
if (ff)
txtNum2.Text += "1";
}
private void txtNum1_TextChanged(object sender, EventArgs e)
{
}
private void txtNum2_MouseClick(object sender, MouseEventArgs e)
{
ff = true;
}
}
}
A boolean will work like you've described. Just flag it when the user clicks in either textbox:
private void txtNum1_Click(object sender, EventArgs e)
{
ff = false;
}
private void txtNum2_Click(object sender, MouseEventArgs e)
{
ff = true;
}
Now, if ff is false, you want to write to txtNum1, and txtNum2 if ff is true.
For the number buttons, I'd write one Click event, then wire all 10 of your number buttons up to it
private void btn_Click(object sender, EventArgs e)
{
if(ff)
txtNum2.Text += (sender as Button).Text;
else
txtNum1.Text += (sender as Button).Text;
}
Assuming each Button's text is simply 1, 2, etc.
In trying to reduce your code, you can see that each operation's function is pretty much identical, except one line. That's a pretty good sign that you can refactor:
private void btnOperator_Click(object sender, EventArgs e)
{
checkForEmptySpace();
double num1, num2, sum;
num1 = double.Parse(txtNum1.Text);
num2 = double.Parse(txtNum2.Text);
double result = 0;
switch((sender as Button).Name)
{
case "btnSubtract":
result = num1 - num2;
break;
case "btnAdd":
//...
}
txtAnswer.Text = Convert.ToString(sum);
}
I would recommend using the Enter event because this is where the control gains focus. Here is some sample code that may help out:
private void OnEnter(object sender, EventArgs e)
{
if (sender == this.textBox1)
{
if (this.textBox1.Text == "")
{
this.textBox1.Text = "0";
if (textBox2.Text == "0")
this.textBox2.Text = "";
}
}
else
{
if (this.textBox2.Text == "")
{
this.textBox2.Text = "0";
if (textBox1.Text == "0")
this.textBox1.Text = "";
}
}
}
Then all you would have to do to apply the event to your textboxes is this:
textBox1.Enter += OnEnter;
textBox2.Enter += OnEnter;
I also agree with Jonesy that you should work on abstracting your code to promote reusability.

Entering an "If" statement where it shouldn't [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
This code should monitor the user's keystrokes and stops him if s\he types a the wrong character .Yet when it comes to the if statement where it should compare to charecter everything just goes wrong
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.Collections;
using System.IO;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
void Rest()
{
counter = -1;
txt1.Enabled = true;
txt2.Enabled = true;
txt3.Enabled = true;
txt4.Enabled = false;
txt5.Enabled = true;
btn2.Enabled = false;
btn1.Enabled = true;
pass = "";
txt4.Clear();
Dic.Clear();
turns = 0;
}
string path;
int counter = -1;
string pass;
Dictionary<char, letterInfo> Dic;
int turns = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (counter < pass.Length) { MessageBox.Show("WrongInput(Shorter) !!! "); Rest(); }
else
{
turns++;
if (turns == Convert.ToInt32(txt1.Text))
{
MessageBox.Show("Test is Done ");
/*Writting files */
Rest();
}
}
}
counter++;
if (counter >= pass.Length) { MessageBox.Show("WrongInput !!!exceded length "); Rest(); }
if ((char)e.KeyValue != pass[counter]) { MessageBox.Show("WrongInput !!!Wrong charecter " + ((char)e.KeyValue).ToString() + " " + pass[counter].ToString()); Rest(); }
if (Dic.ContainsKey((char)e.KeyValue))
{
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
else
{
Dic.Add((char)e.KeyValue, new letterInfo());
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
Dic[(char)e.KeyValue].end.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
private void button1_Click(object sender, EventArgs e)
{
string start = "";
string end = "";
string letter = "";
string all;
foreach (KeyValuePair<char, letterInfo> pair in Dic)
{
start = start + " " + pair.Value.start[0];
end = end + " " + pair.Value.end[0];
letter = letter + " " + pair.Key;
}
all = letter + "\n" + start + "\n" + end;
MessageBox.Show(all);
}
private void button2_Click(object sender, EventArgs e)
{
try
{
txt1.Enabled = false;
txt2.Enabled = false;
txt3.Enabled = false;
txt4.Enabled = true;
txt5.Enabled = false;
btn2.Enabled = true;
btn1.Enabled = false;
pass = txt2.Text;
path = txt3.Text;
counter = Convert.ToInt32(txt1.Text);
Dic = new Dictionary<char, letterInfo>();
/* if (!File.Exists(path))
{
MessageBox.Show("Error..File not found");
Rest();
}Code to handle the xls files */
}
catch (Exception s)
{ MessageBox.Show(s.Message); }
}
}
}
This is the function where the problem occurs
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (counter < pass.Length)
{
MessageBox.Show("WrongInput(Shorter) !!! "); Rest();
}
else
{
turns++;
if (turns == Convert.ToInt32(txt1.Text))
{
MessageBox.Show("Test is Done ");
/*Writting files */
Rest();
}
}
}
counter++;
if (counter >= pass.Length)
{
MessageBox.Show("WrongInput !!!exceded length "); Rest();
}
if ((char)e.KeyValue != pass[counter])
{
MessageBox.Show("WrongInput !!!Wrong charecter "+((char)e.KeyValue).ToString()+" "+pass[counter].ToString()); Rest();
}
if (Dic.ContainsKey((char)e.KeyValue))
{
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
else
{
Dic.Add((char)e.KeyValue, new letterInfo());
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
}
And those are the problematic if statements
counter++;
if (counter >= pass.Length)
{
MessageBox.Show("WrongInput !!!exceded length "); Rest();
}
if ((char)e.KeyValue != pass[counter])
{
MessageBox.Show("WrongInput !!!Wrong charecter "+((char)e.KeyValue).ToString()+" "+pass[counter].ToString()); Rest();
}
You enter into if (counter >= pass.Length) because:
counter = -1; //starts at -1
pass = ""; //starts at empty string (length of zero)
Neither of these variables change in your code until:
counter++; //counter is now 0
counter is now equal to pass.Length. So the if statement is true and "WrongInput !!!exceded length " is printed.
You dont set the value of pass until button 2 is clicked. So on each keypress event that is fired, the pass value is empty.
In if ((char)e.KeyValue != pass[counter]) you are trying to compare the key entered, with the character number in pass. pass is empty and counter increments until you hit button 2. So e.Keyvalue will not equal pass[counter] every time.

Allowing only Digits in a textbox not working? C#

I have a question about a small practice program I'm working on. I have almost no experience with C#, and a little bit of experience with Visual Basic. The problem I'm having has to do with only allowing numbers in the text box. I succeeded in doing so in another program, but for some reason it isn't working with relatively the same code.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
Double TextBoxValue;
TextBoxValue = Convert.ToDouble(txtMinutes.Text);
TextBoxValue = Double.Parse(txtMinutes.Text);
{
Double Answer;
if (TextBoxValue > 59.99)
{
Answer = TextBoxValue / 60;
}
else
{
Answer = 0;
}
{
lblAnswer.Text = Answer.ToString();
}
}
}
private void txtHours_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber (e.KeyChar) && Char.IsControl(e.KeyChar))
{
e.Handled = true;
}
}
}
}
If there are other errors in my code that anyone here can correct me on, that is also appreciated. Thanks in advance.
You've got the checks inverted. What your code does is to cancel input if the new character is a number AND if it's a control character.
if (!char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar))
e.Handled = true;
Your logic is incorrect. It states "if the pressed key is a number and a control character.. then i've handled it". What you want is "if the pressed key is NOT a number, I've handled it".
if (!char.IsNumber(e.KeyChar)) {
// ...
private void txtHours_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
e.Handled = true;
// only allow one decimal point
if (e.KeyChar == '.'
&& (txtHours).Text.IndexOf('.') > -1)
e.Handled = true;
}

Categories