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

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.

Related

Sum textboxes to other textbox wpf C#

I have i wpf form with 3 textboxes there i should write how many tickets, then i want to multiply that number with a value
At the end i have another textbox there i want the sum from the 3 textboxes even if only 1 has value
i have tried this:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString();
}
Cant get it to work
Please help
To convert a string value to an integer value you may use int.Parse method. On the other hand this method (also Convert.ToInt32) requires you making sure that string is always in a good format to get converted. If you are not sure and/or you know that the string may be not in correct format, you may use int.TryParse method, which returns true/false value, stating whether the convert was succesful also giving out required value if it was successful. If it fails you get default value - 0.
If all textboxes follow same procedure you may create only one TextChanged event and bind it to all of them.
private void textBox1_TextChanged(object sender, EventArgs e)
{
int sum = 0;
if (!string.IsNullOrEmpty(textBox1.Text) && int.TryParse(textBox1.Text, out int gold_ticket_count))
{
sum += 120 * gold_ticket_count;
}
if (!string.IsNullOrEmpty(textBox2.Text) && int.TryParse(textBox2.Text, out int silver_ticket_count))
{
sum += 60 * silver_ticket_count;
}
if (!string.IsNullOrEmpty(textBox3.Text) && int.TryParse(textBox3.Text, out int big_show_ticket_count))
{
sum += 500 * big_show_ticket_count;
}
// do smth with the sum...
}
Check if I named textBoxes correctly. It is a good practise to give your controls a meaningful name.
int.Parse doc: https://learn.microsoft.com/en-us/dotnet/api/system.int32.parse?view=net-6.0
int.TryParse doc: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-6.0
an ugly, quick and dirty but working solution:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private int sum1;
private int sum2;
private int sum3;
private int overallSum;
private void tb1_TextChanged(object sender, TextChangedEventArgs e)
{
if (int.TryParse(tb1.Text, out int tb1Value))
sum1 = tb1Value * 120;
else
sum1 = 0;
sum_1.Text = sum1.ToString();
RecalcOverallSum();
}
private void tb2_TextChanged(object sender, TextChangedEventArgs e)
{
if (int.TryParse(tb2.Text, out int tb1Value))
sum2 = tb1Value * 120;
else
sum2 = 0;
sum_2.Text = sum2.ToString();
RecalcOverallSum();
}
private void tb3_TextChanged(object sender, TextChangedEventArgs e)
{
if (int.TryParse(tb3.Text, out int tb1Value))
sum3 = tb1Value * 120;
else
sum3 = 0;
sum_3.Text = sum3.ToString();
RecalcOverallSum();
}
private void RecalcOverallSum()
{
overallSum = sum1 + sum2 + sum3;
overall_sum.Text = overallSum.ToString();
}
}
BTW: I would recommend using MVVM instead of code behind, but I know it wasn't the question

Simple Calculator in C# Forms with Running Total

I am studying online for a generalized degree and we are tasked with developing a simple calculator using .Forms
I was able to create the GUI quite simply, but am struggling with the development in coding a variable that tracks the running total, and allows the user to execute more than one operation.
Currently, my code allows for two inputs and 1 operation. Once totaled, if the user selects another number to operate, the code simply drops the first input and relpaces it with the second original input, then takes the third input and replaces the second input for the new calculation.
for example, if I wanted to add 3 + 6, my calculator would give me 9, but if I then press + 4, instead of getting 13 (3+6+4, or better yet, 9+4) I get 10 (6+4)
I'm hoping someone can point me in the correct direction to create a variable for a running total that tracks the total after an operation is executed and then allows the user to continue performing operations without having to clear the results of only two inputs.
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 IT232M2_McCarver_Par1
{
public partial class Calculator : Form
{
string input = string.Empty;
string operand1 = string.Empty;
string operand2 = string.Empty;
char operation;
double result = 0.0;
public Calculator()
{
InitializeComponent();
}
private void button11_Click(object sender, EventArgs e)
{
this.lblDisplay.Text = "";
input += 6;
this.lblDisplay.Text += input;
}
private void button10_Click(object sender, EventArgs e)
{
this.lblDisplay.Text = "";
input += 1;
this.lblDisplay.Text += input;
}
private void cmdZero_Click(object sender, EventArgs e)
{
this.lblDisplay.Text = "";
input += 0;
this.lblDisplay.Text += input;
}
private void cmdTwo_Click(object sender, EventArgs e)
{
this.lblDisplay.Text = "";
input += 2;
this.lblDisplay.Text += input;
}
private void cmdThree_Click(object sender, EventArgs e)
{
this.lblDisplay.Text = "";
input += 3;
this.lblDisplay.Text += input;
}
private void cmdFour_Click(object sender, EventArgs e)
{
this.lblDisplay.Text = "";
input += 4;
this.lblDisplay.Text += input;
}
private void cmdFive_Click(object sender, EventArgs e)
{
this.lblDisplay.Text = "";
input += 5;
this.lblDisplay.Text += input;
}
private void cmdSeven_Click(object sender, EventArgs e)
{
this.lblDisplay.Text = "";
input += 7;
this.lblDisplay.Text += input;
}
private void cmdEight_Click(object sender, EventArgs e)
{
this.lblDisplay.Text = "";
input += 8;
this.lblDisplay.Text += input;
}
private void cmdNine_Click(object sender, EventArgs e)
{
this.lblDisplay.Text = "";
input += 9;
this.lblDisplay.Text += input;
}
private void cmdClear_Click(object sender, EventArgs e)
{
this.lblDisplay.Text = "";
this.input = string.Empty;
this.operand1 = string.Empty;
this.operand2 = string.Empty;
}
private void cmdAdd_Click(object sender, EventArgs e)
{
operand1 = input;
operation = '+';
input = string.Empty;
}
private void cmdSubtract_Click(object sender, EventArgs e)
{
operand1 = input;
operation = '-';
input = string.Empty;
}
private void cmdMultiply_Click(object sender, EventArgs e)
{
operand1 = input;
operation = '*';
input = string.Empty;
}
private void cmdDivide_Click(object sender, EventArgs e)
{
operand1 = input;
operation = '/';
input = string.Empty;
}
private void cmdEqual_Click(object sender, EventArgs e)
{
string runningTotal = result.ToString();
operand2 = input;
double num1, num2;
double.TryParse(operand1, out num1);
double.TryParse(operand2, out num2);
if (operation == '+')
{
result = num1 + num2;
lblDisplay.Text = result.ToString();
}
else if (operation == '-')
{
result = num1 - num2;
lblDisplay.Text = result.ToString();
}
else if (operation == '*')
{
result = num1 * num2;
lblDisplay.Text = result.ToString();
}
else if (operation == '/')
{
if (num2 != 0)
{
result = num1 / num2;
lblDisplay.Text = result.ToString();
}
else
{
lblDisplay.Text = "Cant /Zero";
}
}
}
}
}
As this is an assignment I would expect your code to contain a lot more comments, detailing your algorithm
I think you need to think about how a real calculator works. I assume you're making a simple one where any operation can trigger a calculate if both operands are set - after the calculation if you put the result in operand1 and unset operand2:
Imagine the user presses 1+2+4=
Set operand1 to 1
Set operation to +
Set operand2 to 2
Both operands are set so calculate, setting operand1 to 4 and unsetting operand2 and operator
Set operation to +
Calculate because = is pressed but don't unset operand2 (because the user can hammer = and add 4 each time)
Consider having a Calculate method that takes a Boolean indicating if it should unset operand2/operator or not. Calculate should always transfer the result of the op into operand1. Whether the operator is set or not should be used to determine if it's operand1 or operand2 that the user is typing. Personally I would do away with input and concatenate operand1 and 2 directly. I'd make the decision as to which to extend in the click handler. I'd have a dedicated variable for when equals had been recently pressed that will unset everything if the user presses a number button after pressing equals, or keeps operand1 and sets a new operation and insets operand2 if it's an operation that the user presses after equals
There are other things we could clean up in your code. This fragment had me puzzled for a while:
private void cmdEight_Click(object sender, EventArgs e)
{
this.lblDisplay.Text = "";
input += 8;
this.lblDisplay.Text += input;
}
This would be more logical:
private void cmdEight_Click(object sender, EventArgs e)
{
input += 8;
lblDisplay.Text = input:
}
But really, if your button just has 8 as its text you can do this:
private void cmdAny_Click(object sender, EventArgs e)
{
input += (sender as Button).Text;
lblDisplay.Text = input:
}
And every button uses this same handler
If you're making a calculator that understands multiply and divide are done before add and subtract you're going to have to store all the operands and operators in a list and then go through the list doing certain operations first upon pressing equals

Why does my C# program display an error for my simple tax calculator appclication?

I am learning C# and need to create a simple tax calculator for school using Visual Studio, and I think I followed most of the instructions, but I keep getting this error:
Error 1 Operator '*' cannot be applied to operands of type 'object' and 'object' C:\Visual Studio 2012\Projects\CS4\CS4Form.cs 83 32 CS4
What am I doing wrong and how can I get it to work? It is supposed to look like a simple windows form app and it should display the calculations in the labels on the right. I did my best to follow the pseudo code but I am not sure what is missing and I have been working on it all day. Here is my 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;
// CS4
namespace CS4
{
public partial class FrmCS4 : Form
{
public FrmCS4()
{
InitializeComponent();
}
// Declare class-level variables and constants
// Class variables are initialized to zero when declared
int cintEmployeeCount;
decimal cdecTotalNetpay;
const decimal cdecFICA_RATE = 0.06M;
const decimal cdecFEDERAL_RATE = 0.15M;
const decimal cdecSTATE_RATE = 0.05M;
const decimal cdecUNION_DUES = 10.00M;
private void Form1_Load(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void label6_Click(object sender, EventArgs e)
{
}
private void label9_Click(object sender, EventArgs e)
{
}
private void label12_Click(object sender, EventArgs e)
{
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void btnCalculate_Click(object sender, EventArgs e)
{
// Declare medthod variables
int decGross;
decimal decFica;
decimal decFederal;
decimal decState;
decimal decNetpay;
// Input
// Use nested try-catch blocks to get input values
try
{
// Get hours worked from textbox
cintEmployeeCount = int.Parse(hoursWorkedBox.Text);
try
{
// Get pay rate from textbox
cdecTotalNetpay = decimal.Parse(payRateBox.Text);
// Calculate gross amount
decGross = intHours * decRate;
// Calculate taxes
decFica = decGross * cdecFICA_RATE;
decFederal = decGross * cdecFEDERAL_RATE;
decState = decGross * cdecSTATE_RATE;
// Calculate net pay
decNetpay = decGross - (decFica + decFederal + decState + cdecUNION_DUES);
// Accumulate summary values
// Calculate average net pay
cdecTotalNetpay += decNetpay;
cintEmployeeCount += 1;
decAverageNetpay = cdecTotalNetpay / cintEmployeeCount;
//Accumulate summary values
//Calculate average net pay
//Display results of calculations and summary values
}
catch (FormatException err)
{
MessageBox.Show("Pay Rate must be numeric. " + err.Message,
"Data Entry Error", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
payRateBox.SelectAll();
payRateBox.Focus();
}
}
catch (FormatException err)
{
MessageBox.Show("Hours worked must be numeric. " + err.Message,
"Data Entry Error", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
hoursWorkedBox.SelectAll();
hoursWorkedBox.Focus();
}
catch (Exception err)
{
MessageBox.Show("Unexpected Error: " + err.Message);
}
}//end method
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void label4_Click(object sender, EventArgs e)
{
}
private void label14_Click(object sender, EventArgs e)
{
}
private void label17_Click(object sender, EventArgs e)
{
}
private void label5_Click(object sender, EventArgs e)
{
}
private void lblFederal_Click(object sender, EventArgs e)
{
}
public object intHours { get; set; }
public object decRate { get; set; }
public decimal decAverageNetpay { get; set; }
private void btnClear_Click(object sender, EventArgs e)
{
// Use Clear or null string "" for TextBoxes, but
// only use null string "" for Labels
hoursWorkedBox.Clear(); // Clear
payRateBox.Clear();
lblGross.Text = "";
lblFica.Text = "";
lblState.Text = "";
lblFederal.Text = "";
lblUnion.Text = "";
lblNet.Text = "";
lblTotalNet.Text = "";
lblEmployee.Text = "";
lblAverage.Text = "";
//Reset Accumulators
cdecTotalNetpay = 0;
cintEmployeeCount = 0;
decAverageNetpay = 0;
hoursWorkedBox.Focus();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
// End of class
// End of namespace
Can anyone please provide some guidance or suggestions and opinions? Again, I am very new at this, and would greatly appreciate any help!
This is line 83:
decGross = intHours * decRate;
The problem is with your typing (that is: data types, not your keyboard skills). Despite your use of Hungarian Notation (which is officially discouraged, btw) your types are incorrect.
decGross is defined as an integer (Int32) when it should be a Decimal
intHours is defined as an Object when it should be an integer
decRate is defined as an Object when it should be a Decimal
The multiplication operation is not defined for Object instances (as it's meaningless).
While the underlying values of the variables may very-well be numeric, the compiler does not know this because you've typed them as Object rather than Decimal. C# is statically typed (at compile-time). I suspect you come from a VB background and are used to VB's late-binding and optional runtime type-checking where performing multipliction of Variant types is allowed.
1)You should cast intHours and decRate into any numeric type
decGross = (int)intHours * (Decimal)decRate;
decGross should be numeric
2)Better way is to change types of intHours and decRate into int and decimal accordingly because of unboxing. https://msdn.microsoft.com/en-us/library/yz2be5wk.aspx
P.S. Sorry if my english is not well

Simple Calculator Application in 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;

Event Handlers in My Converter App Are Not Working

This is the code I have so far:
public partial class Form2 : Form
{
public Double X;
public Form2()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
if(textBox1.Text != "")
X = Convert.ToDouble(textBox1.Text);
X *= 0.001;
label3.Text = "metros";
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
X = Convert.ToDouble(textBox1.Text);
X *= 0.62;
label3.Text = "milhas";
}
private void button4_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
X = Convert.ToDouble(textBox1.Text);
label3.Text = "quilómetros";
}
private void button5_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
X = Convert.ToDouble(textBox1.Text);
X *= 3280,84;
label3.Text = "pés";
}
private void button6_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
X = Convert.ToDouble(textBox1.Text);
X *= 0.17998560115190784737;
label3.Text = "léguas";
}
private void button1_Click(object sender, EventArgs e)
{
textBox2.Text = Convert.ToString(X);
}
This is how the window looks like:
What these do is, when you insert a value on textBox1 (the red one on the middle left of the window), you then select the measurement from the buttons on the right, this will convert the introduced value to kilometres and store it in the variable X and write the chosen measurment on a label to the right of the textBox1.
When you press the "Converter" button, (for now) I wanted the textBox2 to show X, however, this only works when I press "metros" or "pés", if I choose one of the other buttons for the conversion it will simply do nothing...
Does someone have any idea of what's wrong?
And also, side question, how do you select items from the comboBox?
Firstly, if statements only execute the very next statement if their condition is met:
if(textBox1.Text != "")
X = Convert.ToDouble(textBox1.Text); // only run if 'if' is true
X *= 0.001; // always run
label3.Text = "metros"; // always run
The if is associated with the next line. If you want all of the following code to be associated with the if, then you need to open a block:
if(textBox1.Text != "")
{
X = Convert.ToDouble(textBox1.Text);
X *= 0.001;
label3.Text = "metros";
}
To help guard against this, I would advise adopting a consistent style for single-line if statements:
if (something) SomeStatement(); // same line
if (something)
SomeStatement(); // indented
if (something)
{
SomeStatement(); // single statement block
}
It's possible some of your buttons are not working because the link between the event handler methods and the events has been broken. You should open the designer and ensure that each of the buttons has a Click handler assigned.
With respect to the combo-box part of your question: ComboBox.SelectedItem allows you to get or set the selected item. Alternatively you can use ComboBox.SelectedIndex to get or set the index of the item that is selected.

Categories