calculator equal button c# - c#

I have a problem that I want to solve but I don't know how. I made a simple calculator with only a few buttons (Button 1, Button 5, Button+ and Button Equals). I want to make Button Equal repeat the last operation(in this case addition). It works fine when I press 5 + 1 and get the result 6, but after that, when I press Button Equal again, I don't get result 7 but I get 12.
I simply don't know where my mistake is and how to make that repeat function and without adding another button.
I hope someone replies soon and helps my problem. :)
string input = string.Empty;
string oper1 = string.Empty;
string oper2 = string.Empty;
char operacija;
double rezultat = 0.0;
bool rez = false;
bool repeating= false;
private void buttonNumber1_Click(object sender, RoutedEventArgs e)
{
this.textBoxPrikazi.Text = "";
if (rez)
{
input = "1";
rez = false;
}
else
{
input += "1";
}
this.textBoxPrikazi.Text += input;
}
private void buttonNumber5_Click(object sender, RoutedEventArgs e)
{
this.textBoxPrikazi.Text = "";
if (rez)
{
input = "5";
rez = false;
}
else
{
input += "5";
}
this.textBoxPrikazi.Text += input;
}
private void buttonPlus_Click(object sender, RoutedEventArgs e)
{
textBoxPrikazi.Text = "+";
oper1 = input;
operacija = '+';
input = string.Empty;
}
private void buttonEquals_Click(object sender, RoutedEventArgs e)
{
oper2 = input;
double num1, num2;
double.TryParse(oper1, out num1);
double.TryParse(oper2, out num2);
this.textBoxPrikazi.Text = "0";
this.input = string.Empty;
this.oper1 = string.Empty;
this.oper2 = string.Empty;
if (operacija == '+')
{
// x = 1 + 5
rezultat = num1 + num2;
textBoxPrikazi.Text = rezultat.ToString();
// for repeating
if (repeating== true)
{
// 6 = 6
rezultat = num2;
// 6+ 6 = 12
textBoxPrikazi.Text = (rezultat + num2).ToString();
repeating= false;
}
}
if (rezultat == 0)
{
textBoxPrikazi.Text = "0";
}
else
{
input = rezultat.ToString();
rez = true;
repeating= true; // for repeating
}
}
}

Related

How to enable GetAsyncKeyState using char?

Good morning, I would like to "enable" the functions from GetAsyncKeyState from a button that is a char
ps. I am making a AutoClicker for game. (sorry for bad English xd)
example:
private void siticoneButton5_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 27)
{
siticoneButton5.Text = "Zbinduj";
keyRegisteringBool = false;
}
if (keyRegisteringBool)
{
siticoneButton5.Text = "Bind: " + e.KeyChar.ToString();
char bind = e.KeyChar;
keyRegisteringBool = false;
}
}
//here i have a void with a function
int min = Convert.ToInt32(materialSingleLineTextField1.Text);
int max = Convert.ToInt32(materialSingleLineTextField2.Text);
Random rand = new Random();
int cps = rand.Next(min, max);
while (true)
{
if (GetAsyncKeyState() < 0) //here I want to start this by key down a char.
{
bot.Mouse.LeftButtonClick();
Thread.Sleep(1000 / cps);
}
}
```
Thanks in advace

How to add space between bytes in textbox?

I have one textbox which gets only bytes and I want to add space between every bytes.
What I have done so far?
public int a=0;
public char c;
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
c = e.KeyChar;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
a = textBox2.TextLength % 3;
if (c != 0x08 && a==2)
{
a = textBox2.TextLength % 3;
int selectionIndex = textBox2.SelectionStart;
textBox2.Text = textBox2.Text.Insert(selectionIndex, " ");
textBox2.SelectionStart = selectionIndex + 1; // restore cursor position
}
}
I add space with this code but if I delete some bytes it doesn't add space.
I think there is some issue in 'if' condition.
For example I write 'abcdef' it adds space and write
ab cd ef
then I delete 'cdef' and space it works properly in here.
I write again 'cdef' it doesn't work and result will be like that
abcde f
How can I fix this issue?
I solve the problem with this code.
private void textBox5_TextChanged(object sender, EventArgs e)
{
int selectionIndex = textBox5.SelectionStart;
int chars = textBox5.Text.Length;
int a = chars % 3;
if (a == 2 && c!=0x08)
{
textBox5.Text = textBox5.Text.Insert(selectionIndex, " ");
textBox5.SelectionStart = selectionIndex + 1; // restore cursor position
}
if (chars > 1)
{
if (a == 0 && c == 0x08)
{
textBox5.Text = textBox5.Text.Remove(chars - 1);
textBox5.SelectionStart = selectionIndex + 1;
}
}
}

Broken C# else if returning error page

I am trying to work with if else statements for different things. I need one that pulls the value of a dropdown list to determine what the calculation will be, another that pulls the value of a check box and assigns a calculation, another for input validation for if the number exceeds 32, and the last to give me a value determined by the amount (up to 32) entered into the textbox. I think i've gotten the checkbox statement corrected (guideFee), and the input validation and the one that goes with it seem to be correct already, but I am having trouble assigning the constant decimal values to the dropdown list values and I don't understand why. I have the basetourRate = Convert.ToDecimal(riverTour) and the if statement that follows, but when I run the program I get an error page. I have pasted the whole code. If anyone could help me out i'd greatly appreciate it, thank you!
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void butCalculate_Click(object sender, EventArgs e )
{
//1. Declare Variables
decimal totalBaseTourFee;
decimal totalGuideFee;
decimal totalWeekendSurcharge;
decimal subtotal;
decimal salesTaxCharge;
decimal totalCharge;
decimal baseTourRate;
decimal guideFee = 0m;
bool isGuidedTour;
int numberOfRafters;
int numberOfRaftsNeeded;
string riverTour;
string timeOfWeek;
string displayTotalBaseTourFee;
string displayNumberOfRaftsNeeded;
string displayTotalGuideFee;
string displayTotalWeekendSurcharge;
string displaySubtotal;
string displaySalesTaxCharge;
string displayTotalCharge;
const decimal FRENCH_BROAD = 40m;
const decimal NANTAHALA = 30m;
const decimal TUCK = 20m;
const decimal WEEKEND_SURCHARGE = 10M;
const decimal GUIDE_FEE = 35M;
const decimal SALES_TAX_RATE = .07M;
//2. Get Values
numberOfRafters = Convert.ToInt32(txtNumberOfRafters.Text);
riverTour = ddlTour.SelectedValue;
isGuidedTour = chkGuided.Checked;
timeOfWeek = rblDay.SelectedValue;
Trace.Warn("numberOfRafters = " + numberOfRafters);
Trace.Warn(("isGuidedTour = " + isGuidedTour));
Trace.Warn("riverTour = " + riverTour);
Trace.Warn("timeOfWeek = " + timeOfWeek);
//Input Validation
if (numberOfRafters > 32)
{
Console.WriteLine("Sorry, we can't handle this large of a group!");
return;
}
//3. Do Calculations
baseTourRate = Convert.ToDecimal(riverTour);
if (riverTour == "FB")
{
baseTourRate = FRENCH_BROAD;
}
else if (riverTour == "NH")
{
baseTourRate = NANTAHALA;
}
else if (riverTour == "TK")
{
baseTourRate = TUCK;
}
if (isGuidedTour == true)
{
guideFee = GUIDE_FEE;
}
else if (!isGuidedTour == false)
{
guideFee = 0;
}
totalBaseTourFee = numberOfRafters * baseTourRate;
numberOfRaftsNeeded = numberOfRafters;
if (numberOfRafters <= 8)
{
numberOfRaftsNeeded = 1;
}
else if (numberOfRafters <= 16)
{
numberOfRaftsNeeded = 3;
}
else if (numberOfRafters <= 24)
{
numberOfRaftsNeeded = 3;
}
else if (numberOfRafters <=32)
{
numberOfRaftsNeeded = 4;
}
totalGuideFee = numberOfRaftsNeeded * guideFee;
totalWeekendSurcharge = numberOfRafters * WEEKEND_SURCHARGE;
subtotal = totalBaseTourFee + totalGuideFee + totalWeekendSurcharge;
salesTaxCharge = subtotal * SALES_TAX_RATE;
totalCharge = subtotal + salesTaxCharge;
//4. Display Results
displayTotalBaseTourFee = totalBaseTourFee.ToString("C") + "<br>";
displayNumberOfRaftsNeeded = numberOfRaftsNeeded.ToString("C") + "<br>";
displayTotalGuideFee = totalGuideFee.ToString("C") + "<br>";
displayTotalWeekendSurcharge = totalWeekendSurcharge.ToString("C") + "<br>";
displaySubtotal = subtotal.ToString("C") + "<br>";
displaySalesTaxCharge = salesTaxCharge.ToString("C") + "<br>";
displayTotalCharge = totalCharge.ToString("C") + "<br>";
lblTotalBaseTourFee.Text = displayTotalBaseTourFee;
lblNumberOfRafts.Text = displayNumberOfRaftsNeeded;
lblTotalGuideFee.Text = displayTotalGuideFee;
lblTotalWeekendSurcharge.Text = displayTotalWeekendSurcharge;
lblSubtotal.Text = displaySubtotal;
lblSalesTaxCharge.Text = displaySalesTaxCharge;
lblTotalCharge.Text = displayTotalCharge;
}
protected void butClear_Click(object sender, EventArgs e)
{
//Clear TextBox and Label
txtNumberOfRafters.Text = "";
lblTotalBaseTourFee.Text = "";
lblNumberOfRafts.Text = "";
lblTotalGuideFee.Text = "";
lblTotalWeekendSurcharge.Text = "";
lblSubtotal.Text = "";
lblSalesTaxCharge.Text = "";
lblTotalCharge.Text = "";
ddlTour.SelectedIndex = -1;
rblDay.SelectedIndex = -1;
chkGuided.Checked = false;
//Set focus back to name textbox
txtNumberOfRafters.Focus();
}
}
The one thing that sticks out to me is the Convert.ToDecimal(...) call.
baseTourRate = Convert.ToDecimal(riverTour);
if (riverTour == "FB")
{
baseTourRate = FRENCH_BROAD;
}
else if (riverTour == "NH")
{
baseTourRate = NANTAHALA;
}
else if (riverTour == "TK")
{
baseTourRate = TUCK;
}
You are attempting to convert a string to a decimal but then you are comparing that string to a string. My guess is that riverTour is not really a decimal and therefore you are getting an exception. Basically, the logic does not make sense. Convert.ToDecimal will throw an exception if it is not a valid decimal. Therefore, riverTour cannot contain a convertible value to decimal and a comparable value to FB/NH/TK. What exactly are you trying to accomplish? If you are trying to convert to decimal if it is valid and then check those 3 cases if it is not then you should look into decimal.TryParse(string, out decimal) https://msdn.microsoft.com/en-us/library/9zbda557(v=vs.110).aspx. This might help you achieve what you are trying to do.
If the input is always numeric, then you should consider using NumericUpDown. Or, at the very least, use TryParse methods so you can tell if the input is valid or invalid.
numberOfRafters = Convert.ToInt32(txtNumberOfRafters.Text);
Is also unsafe.

Textbox validation 2 char and 2 integer

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

Increment the number by 1

I would like to see label6 display the number of correct times the user chooses the number. And label7 display the number of times the user choose incorrectly. Its not incrementing by one.
Error 1 Operator '++' cannot be applied to operand of type 'string'
Error 2 Operator '++' cannot be applied to operand of type 'string'
private void button1_Click(object sender, EventArgs e)
{
string correct="0";
string incorrect="0";
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
label3.Text=("Winner");
label6.Text = correct +1;
if (textBox1.Text != label1.Text)
label7.Text = incorrect= +1;
label3.Text=(string.Format("Sorry - You Lose, The number is {0}", label1.Text));
}
Edit (From OP's answer to his own question):
I have tried the ways your suggesting but the number doesnt increase by one everytime I guess wrong.
private void button1_Click(object sender, EventArgs e)
{
int correct=0;
int incorrect=0;
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
{
label3.Text = ("Winner");
label6.Text = (++correct).ToString();
}
else if (textBox1.Text != label1.Text)
{
label7.Text = (incorrect+1).ToString();
label3.Text = (string.Format("Sorry - You Lose, The number is {0}", label1.Text));
}
}
It doesn't look like you're persisting the correct and incorrect
Create Properties:
public int Correct { get; set; }
public int Incorrect { get; set;}
Then:
private void button1_Click(object sender, EventArgs e)
{
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
{
label3.Text=("Winner");
label6.Text = (++this.Correct).ToString();
}
else
{
label3.Text=(string.Format("Sorry - You Lose, The number is {0}", label1.Text));
label7.Text = (++this.Incorrect).ToString();
}
}
You are storing your correct and incorrect variables as string.
Use int instead like this:
int correct = 0;
int incorrect = 0;
and change your code to:
correct++;
label6.Text = correct.ToString();
and:
incorrect++;
label7.Text = incorrect.ToString();
Adding to strings, correct and incorrect will just append the string representation of what's added. You have to convert it to an integer type, then increment, then convert back to string. However it would be easier to just keep these variables as integer instance variables. That way incrementing is trivial and you are actually keeping the correct count and not resetting every time the button gets clicked. (There are actually a number of problems with the code)
// instance variables
private int correct = 0;
private int incorrect = 0;
private void button1_Click(object sender, EventArgs e)
{
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
{
label3.Text=("Winner");
label6.Text = (++correct).ToString(); // convert int to string
}
// indentation does not indicate the block
else //if (textBox1.Text != label1.Text)
{
label3.Text=(string.Format("Sorry - You Lose, The number is {0}", label1.Text));
label7.Text = (++incorrect).ToString();
}
}
Or you can use:
correct = correct + 1; ( I think this is what you were trying to achieve)
incorrect = incorrect + 1;
OR
correct += 1;
incorect += 1;
label6.Text = correct +1;
only sets label6's value to correct + 1; it does not change the value of correct. If you use:
int correct;
label6.Text = (++correct).ToString();
you should see what you want.

Categories