Amateur here making a C# calculator in visual studio and want to save inputs as 'operand1' and 'operand2' such that I can display the history of inputs/calculations. Example of my first thought:
private void twoBtn_Click(object sender, EventArgs e)
{
if (txtBox.Text == "0")
{
txtBox.Text = "2";
}
else
{
txtBox.Text += "2";
}
}
The issue is that it simply adds that to the text box, which is fine for calculations, but I have no way of retrieving that input data after it's cleared.
I've tried setting it up like this:
private void oneBtn_Click(object sender, EventArgs e)
{
if (operand1 == null)
{
operand1 = 1;
txtBox.Text = operand1.ToString();
return;
}
if (operand2 != null) return;
operand2 = 1;
txtBox.Text = operand2.ToString();
}
However, the issue here is that I cannot seem to input an operand which is more than 1 digit, making the only possible operands numbers 1-9. I understand I'm very new to the language and coding in general and would greatly appreciate anyone's insight as to what I'm missing!
Related
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;}
I'm an absolute beginner when it comes to C#. Trying to learn via examples. So I've found myself a nice little calculator tutorial. Everything goes fine up to last moment, the code is working, but it doesn't take multi-digit input like 33. There's a bool statement there for turning arithmetic operations on/off and tutorial instructor figured, that we should put bool = false before the number input/button press (in button_Click).
His code looks like this:
public partial class MainWindow : Window
{
double value = 0;
string operation = "";
bool operation_pressed = false;
public MainWindow()
{
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{
if ((tb.Text == "0") || (operation_pressed == true))
tb.Clear();
operation_pressed = false;
Button b = (Button)sender;
tb.Text += "\n" + b.Content.ToString();
}
private void operator_Click(object sender, RoutedEventArgs e)
{
Button b = (Button)sender;
operation = b.Content.ToString();
value = double.Parse(tb.Text);
operation_pressed = true;
equation.Content = value + " " + operation;
}
private void result_Click(object sender, RoutedEventArgs e)
{
equation.Content = "";
switch(operation)
{
case "+":
tb.Text = "\n" + (value + double.Parse(tb.Text)).ToString();
break;
case "-":
tb.Text = "\n" + (value - double.Parse(tb.Text)).ToString();
break;
case "*":
tb.Text = "\n" + (value * double.Parse(tb.Text)).ToString();
break;
case "/":
tb.Text = "\n" + (value / double.Parse(tb.Text)).ToString();
break;
default:
break;
}
}
private void CE_Click(object sender, RoutedEventArgs e)
{
tb.Text = "\n 0";
}
private void C_Click(object sender, RoutedEventArgs e)
{
tb.Clear();
equation.Content = "";
value = 0;
}
}
It compiles nicely. But when I try to input a multidigit number and follow it with a mathematical operator, it throws an exception for value = double.Parse(tb.Text); that states:
When converting string to DateTime, parse the string to take the date before putting each variable into the DateTime object.
I'm so confused right now. There's no DateTime even involved! And I'm 100% positive, everything is like in the tutorial. What's going on? :/
Any help will be appreciated greatly!
EDIT
Screenshot of actual error:
First of all, you're interpreting the debugger incorrectly. This is not the error message:
When converting string to DateTime, parse the string to take the date before putting each variable into the DateTime object.
Notice how it's listed as "Troubleshooting Tips". In the vast majority of cases, you can ignore it. The error message itself is in a language I don't know, so I can't speak to what it says. But a FormatException essentially means that you're trying to parse a value which can't be parsed.
Your screen shot cuts off some information, but what is the value of tb.Text? Is it one of those "+" strings? If so, then that's your problem.
"+" can't be parsed as a numeric value, because "+" isn't a number.
You can make your code a little more resistant to errors by using TryParse instead of Parse. Something like this:
double result;
if (!double.TryParse(tb.Text, out result))
{
// couldn't parse
}
If the if block isn't entered, then result will contain the successfully parsed value. If it is entered, then the value couldn't be parsed. How you handle that situation is up to you. An error message to the user, a default value instead of the parsed value, etc. That's application logic for you to define.
The point is, tb.Text contains a non-numeric value which you're trying to convert into a numeric value. Hence the error.
Try this code in operator_Click event
Button b = (Button)sender;
operation = b.Text;
value = Convert.ToDouble(tb.text)
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.
I have to detect decimal separator in current windows setting. Im using visual studio 2010, windows form. In particular, if DecimalSeparator is comma, if user input dot in textbox1, I need show zero in textbox2.
I tryed with this code, but not works:
private void tbxDaConvertire_KeyPress(object sender, KeyPressEventArgs e)
{
string uiSep = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator;
if (uiSep.Equals(","))
{
while (e.KeyChar == (char)46)
{
tbxConvertito.Text = "0";
}
}
}
I have tryed also this code, but not work:
private void tbxDaConvertire_KeyPress(object sender, KeyPressEventArgs e)
{
string uiSep = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
if (uiSep.Equals(","))
{
if (e.KeyChar == (char)46)
{
tbxConvertito.Text = "0";
}
}
}
Solution:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char a = Convert.ToChar(Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator);
if (e.KeyChar == a)
{
e.Handled = true;
textBox1.Text = "0";
}
}
That way, when you hit . or , you will have a 0 in your TextBox.
EDIT:
If you want to insert a 0 everytime you hit the decimal separator, this is the code:
char a = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
if (e.KeyChar == a)
{
e.KeyChar = '0';
}
Actually you should be using
CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
instead of
CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator
Using the second one gives you the OS default settings, which might be different then user Regional Locales for particular user account logged to this PC.
Credits to berhir and Grimm for pointing out the [docs]
You shouldn't use a while loop, I think it will freeze the application, use if instead, the problem might be here
I m Working On A windows Form.. I Need my TextBox Not To Accept negative Values ..How Can I Do this..
IS There Any Property Availiable For Doing The same...
You need to write keypress event of textbox like :
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
You can also user numeric updown control to prevent negetive values.
UPDATE :
Ref: Sai Kalyan Akshinthala
My code will not handle the case of copy/paste. User can enter negative values by copy/paste. So I think Sai Kalyan Akshinthala's answer is correct for that case except one small change of Length >= 2.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if(textBox1.Text.Length >= 2)
{
int acceptednumber = Convert.ToInt32(textBox1.Text);
if(acceptednumber < 0)
{
textBox1.Text = "";
MessageBox.Show("-ve values are not allowed");
}
else
{
textBox1.Text = textBox1.Text;
}
}
}
yes you can do write the following code part in textchanged event of textbox
if(textBox1.Text.Length >= 2)
{
int acceptednumber = Convert.ToInt32(textBox1.Text);
if(acceptednumber < 0)
{
textBox1.Text = "";
MessageBox.Show("-ve values are not allowed");
}
else
{
textBox1.Text = textBox1.Text;
}
}
just use min and pattern will not allow to enter a minus value
min="0" pattern="^[0-9]+$" in input type