I am a beginner in C#. I am making a web calculator like Microsoft Desktop calculator with the help of asp.net. But I'm stuck at one place. My code for Plus, minus, multiply or div is like:
protected void btnPlus_Click(object sender, EventArgs e)
{
if (txtBox1.Text.EndsWith("+"))
{
txtBox1.Text = txtBox1.Text;
}
else
{
txtBox1.Text = txtBox1.Text + "+";
ViewState["Operation"] = "+";
}
}
But I want to check this condition for all operations like minus, multiply and divide. I don't want Plus, Minus, Multiply or Div signs appear in the textbox.
You can store all your operators in a string constant and check if the last character is contained in that string:
private const string OPERATORS = "+-/*";
protected void btnPlus_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtBox1.Text) || // check if string is empty
OPERATORS.Contains(txtBox1.Text.Last())) // or if last character is a operator
{
txtBox1.Text = txtBox1.Text;
}
else
{
txtBox1.Text = txtBox1.Text + "+";
ViewState["Operation"] = "+";
}
}
You can do something like the following:
Extract last character
Based on the character assign operator to the view state
If it is any operator then remove them from the textbox
Finally do the operation
if (txtBox1.Text != "")
{
char last_char = txtBox1.Text[txtBox1.Text.Length - 1];
switch (last_char)
{
case '+':
ViewState["Operation"] = "+";
txtBox1.Text.Remove(txtBox1.Text.Length - 1);
break;
case '-':
ViewState["Operation"] = "-";
txtBox1.Text.Remove(txtBox1.Text.Length - 1);
break;
// do the same for all operators
default:
break;
}
}
Related
I am trying my hand at a self teaching project by creating a calculator. I am having trouble getting my backspace to update the text in my textbox. My goal is to be able to Backspace using my backspace button and add a number afterward and having my result being exactly whats expected with any backspace i.e.
(1) string of 701
(2) Backspace used
(3) Adding 4 to the string
(4) return 704
What I am thinking is that when I click the button it is returning a new string and when I enter a new number, it is updating the old string. I have tried this code in the btnBck_Click function as well as what I am showing in my current code(the BackSpaceFunction(); is my attempt to tell the program to return the updated string).
private void btnBck_Click(object sender, EventArgs e)
{
BackSpaceFunction();
}
private string BackSpaceFunction()
{
string textBoxText = textBox1.Text;
textBoxText = textBox1.Text.Remove(textBoxText.Length - 1);
if (textBox1.Text.Length >= 1)
{
textBox1.Text = textBox1.Text.Replace(textBox1.Text, textBoxText);
return textBox1.Text;
}
else if (textBox1.Text.Length == 0)
{
textBox1.Text = "0";
input = string.Empty;
operand1 = string.Empty;
operand2 = string.Empty;
}
return textBox1.Text;
}
(Please understand my excessive explaining and use of examples is to make sure everyone can understand in case I myself missed the point. Thank you in advance)
I am having trouble getting my backspace to update the text in my textbox
The TextBox control supports use of the backspace key directly. As long as the TextBox has the input focus, pressing the backspace key will delete the character just before the current insertion point.
Your code example is incomplete, but it looks like you have a separate Button object that is intended to provide similar functionality. You aren't taking into account the insertion point for the TextBox, so presumably you just always want to remove the last character. If that's the case, your method is far more complicated than it needs to be. You can just use string.Substring() to remove the last character:
private string BackSpaceFunction()
{
if (textBox1.Length > 0)
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1);
}
if (textBox1.Text.Length == 0)
{
textBox1.Text = "0";
input = string.Empty;
operand1 = string.Empty;
operand2 = string.Empty;
}
return textBox1.Text;
}
(You never actually use the return value, so it's not clear why the method has a return value. But I left that in because it's not inherently a problem.)
So to answer my own question, I took the time to try and figure it out for myself. I ended up succeeding and found that this code worked (look at the "if" portion of my if statement).
private void btnBck_Click(object sender, EventArgs e)
{
BackSpaceFunction();
}
private string BackSpaceFunction()
{
//textBoxText = textBox1.Text.Remove(textBoxText.Length - 1);
if (textBox1.Text.Length >= 1)
{
string textBoxText = textBox1.Text.Remove(textBox1.Text.Length - 1);
string updatedText = textBox1.Text = textBox1.Text.Replace(textBox1.Text, textBoxText);
textBox1.Text = updatedText;
input = string.Format(textBox1.Text, updatedText);
operand1 = string.Format(textBox1.Text, updatedText);
operand1 = string.Format(textBox1.Text, updatedText);
}
else if (textBox1.Text.Length == 0)
{
textBox1.Text = "0";
input = string.Empty;
operand1 = string.Empty;
operand2 = string.Empty;
}
return textBox1.Text;
}'''
I'm not exactly sure why I had to use Format for input, operand1, and operand2 but it ended up doing exactly what I needed. If there are any explanations as to why this worked I will gladly accept the learning opportunity. :)
I am beginner , am trying to create a calculator. the way of the code working is there is a method for summing and one for subtraction ETC.
when i call the subtraction method unwanted minus appears before the answer in the textbox ( i know my code could be using harder way to do the same purpose but i am just beginner trying to do some code )
double rat;
byte operations;
public void TheEqualMinus(double earlier) //Substraction Operation Method
{
double _minus;
_minus = Convert.ToDouble(result.Text);
double last = _minus - earlier;
result.Text = last.ToString();
}
private void button15_Click(object sender, EventArgs e)
{
//The Subtract Button
operations = 2;
rat = Convert.ToDouble(result.Text);
label1.Text = rat + " -";
result.Text = "";
}
private void button4_Click(object sender, EventArgs e)
{
// equal button
NewText = true; //boolean to newtext
switch (operations)
{
case (1): //addition
TheEqualSum(rat);
label1.Text = "";
break;
case (2): //substraction
TheEqualMinus(rat);
label1.Text = "";
break;
}
}
and the answer output becomes " - The Correct Answer i want "
ex. 9-6 = -3
so any ideas how to remove this minus ?
As per the comments above, this was fixed by simply changing this:
double last = _minus - earlier;
to this:
double last = earlier - _minus;
I am making a calculator to gain some experience with C#, atm i have one textbox ontop of one another, the lower one is called calculation; i want this one to show the sum being calculated. The text box on top is called result and i obviously want that to display the result; the result box works fine. I want the lower text box ( called calculation ) to display the + symbol which it wont let me do and at the moment i am only able to show the digits. I assume this is a data type problem. Any help/advice? thank you! (I'm sorting this out before moving onto the other symbols and eventually putting it into a switch case :) )
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double num1 = 0;
double num2 = 0;
private void Clearbtn_Click(object sender, EventArgs e)
{
Calculation.Clear();
Result.Clear();
}
private void Numericclick(object sender, EventArgs e)
{
Button button = (Button)sender;
Calculation.Text = Calculation.Text + button.Text;
}
private void Plusbtn_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(Calculation.Text);
Result.Show();
}
private void Equalsbtn_Click(object sender, EventArgs e)
{
num2 = num1 + double.Parse(Calculation.Text);
Result.Text = num2.ToString();
num1 = 0;
}
}
}
If you use the (+) operator with strings it concatenates them together.
This line Calculation.Text = Calculation.Text + button.Text;
In C# 6 will be this:
Calculation.Text = $"{Calculation.Text} + {button.Text}";
Lower than C# 6:
Calculation.Text = string.Format("{0} + {1}", Calculation.Text, button.Text);
String Concatenation Documentation: HERE
Example of difference between the operand + and as a string "+":
//+ operand concats string
var text = "abc";
var text2 = "def";
var result = text + text2;
//result -> "abcdef"
var result2 = text + "+" + text2;
//result -> "abc+def"
So, I have made a calculator in C# but it cannot calculate decimal numbers.
It works perfectly fine when clicking on for example the buttons: 6 then . (this is a dot) then 5. But as soon as I click on the "+"-button (or any other operator) afterwards in the form, the program stops and I get a message saying that
"An unhandled exception of type 'System.FormatException' occured in
mscorlib.dll. The input string was not in a correct format".
I don't know exactly how to solve this. Is there anyone that knows how to solve this problem?
Here is my code:
namespace Kalkylator{
public partial class Form1 : Form{
String operation = ""; //the operation we will use
Double resultat = 0; //the result we will get
bool finished = false; //if false, we have not pressed the "=" button yet
public Form1(){
InitializeComponent();
}
//
private void button_click(object sender, EventArgs e){
if (finished == true){ //if we press any operator, clear the textbox-window so new numbers can be entered
textBoxFonster.Clear();
}
finished = false; //we are not done with the calculation
Button b = (Button)sender;
if (b.Text == "."){
if (!textBoxFonster.Text.Contains(".")){
textBoxFonster.Text = textBoxFonster.Text + b.Text;
}
}
else{
textBoxFonster.Text = textBoxFonster.Text + b.Text; //writes the number in the textBox
}
}
private void operator_click(object sender, EventArgs e)
{
Button b = (Button)sender;
operation = b.Text; //the operation we will perform is the operatorButton we will press
resultat = Double.Parse(textBoxFonster.Text); //HERE IS WHERE THE PROGRAM GIVES ME THE ERROR.
finished = true; //we are done with the calculation
}
private void clear_click(object sender, EventArgs e)
{
textBoxFonster.Text = ""; //clear the window from all text
resultat = 0; //clear the value of resultat and set it to 0
}
private void LikaMed_click(object sender, EventArgs e)
{
switch(operation){
case "+": //add the result with the text in the textBox
textBoxFonster.Text = (resultat + Double.Parse(textBoxFonster.Text)).ToString();
break;
case "-":
textBoxFonster.Text = (resultat - Double.Parse(textBoxFonster.Text)).ToString();
break;
case "*":
textBoxFonster.Text = (resultat * Double.Parse(textBoxFonster.Text)).ToString();
break;
case "%":
textBoxFonster.Text = (resultat / Double.Parse(textBoxFonster.Text) * (resultat/100)).ToString();
break;
case "^":
textBoxFonster.Text = (Math.Pow(resultat, Double.Parse(textBoxFonster.Text))).ToString();
break;
case "Log": //takes the 10th log of resultat
textBoxFonster.Text = (Math.Log10(resultat)).ToString();
break;
case "Sqrt":
textBoxFonster.Text = (Math.Sqrt(resultat)).ToString();
break;
case "/": //divide the result with the text in the textBox if that text is not 0. If so, show an error message
if ((Double.Parse(textBoxFonster.Text)) != 0){
textBoxFonster.Text = (resultat / Double.Parse(textBoxFonster.Text)).ToString();
}
else{ //show error in MessageBox
MessageBox.Show("Cannot divide by 0!");
}
break;
default:
break;
}
finished = true; //this will clear the result textbox when clicking another number after the equal sign has been clicked
}
}
}
Don't use Double.Parse without specifying the Culture.
Change:
switch(operation){
case "+": //add the result with the text in the textBox
textBoxFonster.Text = (resultat + Double.Parse(textBoxFonster.Text)).ToString();
break;
case "-":
textBoxFonster.Text = (resultat - Double.Parse(textBoxFonster.Text)).ToString();
break;
to:
Double operand1=resultat;
Double operand2=0;
Double.TryParse(textBoxFonster.Text,NumberStyles.Float,CultureInfo.InvariantCulture,out operand2);
switch(operation){
case "+": //add the result with the text in the textBox
textBoxFonster.Text = (operand1 + operand2).ToString();
break;
case "-":
textBoxFonster.Text = (operand1 - operand2).ToString();
break;
Alternatively, you could actually support multiple cultures, and change this code:
if (b.Text == "."){
if (!textBoxFonster.Text.Contains(".")){
textBoxFonster.Text = textBoxFonster.Text + b.Text;
}
}
to this:
if (b.Text == System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator){
if (!textBoxFonster.Text.Contains(System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator)){
textBoxFonster.Text = textBoxFonster.Text + b.Text;
}
}
i need to validate textbox1 as 2 alphabets and 2integer only i.e) ab11
how i can set it my text box only accept 2 chars and 2 integers.
Please help me...
if:
string myString = textbox1.Text;
Then to validate:
If (Regex.IsMatch(myString, "^[A-Za-z]{2}[0-9]{2}$")))
{
return true;
}
else
{
return false;
}
private void textBox2_Validating(object sender, CancelEventArgs e)
{
var cn = textBox2.Text.Where(c => char.IsLetter(c)).Count();
var cd = textBox2.Text.Where(c => char.IsNumber(c)).Count();
if (cn >= 2 && cd >= 2)
{
//Success, Do Stuff
}
else
{
e.Cancel = true;
}
}
This should work.
private void textBox1_TextChanged(object sender, EventArgs e)
{
TextBox tb=sender as TextBox;
string text=tb.Text;
switch (text.Length)
{
case 1:
if (!char.IsLetter(text[0]))
tb.Text = "";
break;
case 2:
if (!char.IsLetter(text[1]))
tb.Text = text.Remove(1);
break;
case 3:
if (!char.IsNumber(text[2]))
tb.Text = text.Remove(2);
break;
case 4:
if (!char.IsNumber(text[3]))
tb.Text = text.Remove(3);
break;
default:
if(text.Length>4)
tb.Text = text.Substring(0, 4);
break;
}
textBox1.Select(tb.Text.Length, 0);
}
string str = textBox1.Text;
if (Regex.IsMatch(str, #"^(([A-Z]|[a-z])([A-Z]|[a-z])\d\d)$"))
{
MessageBox.Show("Valid");
}
Reference: Regex Class