C# Calculator typing by pressing buttons - c#

I am studying C# now, so i am making some kind of exercises to get used to C# syntax and learn better. I decided to make a calculator looking alike the normal windows calculator.
I created only one button "1" and one textbox.
I want to make this button write 1 in textbox when I press it and also make an int variable equal to the number in the textbook, to make the calculation later. So I can't either change "int a"'s value or change text in the textbox, it always shows 01, because a always equals to 0.
How can I make the program, both show the correct numbers and change the value of a correctly?
For example how can i make the program show eleven in the textbox when i press button twice and also change "int a"'s value to 11?
public partial class Form1 : Form
{
int a;
string Sa;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Sa = a.ToString() + "1";
textBox1.Text = Sa;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}

private void button1_Click(object sender, EventArgs e)
{
textBox1.Text += "1";
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
a = Int32.Parse(textBox1.Text);
}
just it.. Change text on textBox every button click, and change variable a every textBox changed.

The value could then be set using
a = int.Parse(Sa);
textBox1.Text = Sa.TrimStart('0');
Although if you'd like to be more efficient about it,
a = a * 10 + 1;
not have Sa at all,
textBox1.Text = a.ToString();
If you run into integer overflows, you should use BigInteger.

You have several options:
Make int a nullable int. That way you can check if int is already set
int? a;
if ( a.HasValue )
{
}
else
{
}
Check if the Text property of textBox1 is empty (which means you don't have to append a to it)
if ( textBox1.Text == string.Empty)
{
}
else
{
}

public void btnOne_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnOne.Text;
}
private void btnTwo_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnTwo.Text;
}
// etc

for any button you want to append text to the text box set the click property to btn_Click then pt this code inside the method
private void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
// This will assign btn with the properties of the button clicked
txt_display.Text = txt_display.Text + btn.Text;
// this will append to the textbox with whatever text value the button holds
}

Related

Clicking the same button but different action - c#

When i click on a button,text will appear in textbox1 but then i want it to change focus to another textbox(textbox2) and when i click the same button again,display the same text but in textbox2.
private void btna_Click(object sender, EventArgs e)
{
textBox1.Text = ("A");
if (textBox1.Text.Length > 0)
{
textBox2.Focus();
}
If you want to alternate between different TextBoxes in your click event to determine which one to update, you can track them in a private variable, and then just switch which one you're using based on the current value, for example:
private TextBox textBoxToUpdate = null;
private void button1_Click(object sender, EventArgs e)
{
// Swap the textBoxToUpdate between textBox1 and textBox2 each time
textBoxToUpdate = (textBoxToUpdate == textBox1) ? textBox2 : textBox1;
textBoxToUpdate.Text = "A";
}
Another way to do this if you're updating multiple controls is to store them in a list and increment an integer that defines the index to the next item.
// holds the text boxes we want to rotate between
private List<TextBox> textBoxesToUpdate = new List<TextBox>();
private void Form1_Load(object sender, System.EventArgs e)
{
// add some text boxes to our list
textBoxesToUpdate.Add(textBox1);
textBoxesToUpdate.Add(textBox2);
textBoxesToUpdate.Add(textBox3);
textBoxesToUpdate.Add(textBox4);
}
// stores the index of the next textBox to update
private int textBoxToUpdateIndex = 0;
private void button1_Click(object sender, EventArgs e)
{
textBoxesToUpdate[textBoxToUpdateIndex].Text = "A";
// increment the index but set it back to zero if it's equal to the count
if(++textBoxToUpdateIndex == textBoxesToUpdate.Count) textBoxToUpdateIndex = 0;
}

C# Can't find beginners explanation about auto update textbox WITH calculation

I am making a calculation, but then I came up with the idea to automatically make that calculation as I fill in textBox1. How I can call that calculation that is inside button1_Click? I know how to copy to textBox2 what you wrote in textBox1, but my knowledge is to little for to call a whole if statement calculation to auto update Total inside textBox2 when I was writing numbers inside textBox1 without a button.
private void textBox1_TextChanged(object sender, EventArgs e) { }
private void textBox2_TextChanged(object sender, EventArgs e) { }
private void button1_Click(object sender, EventArgs e)
{
aantalgroep = int.Parse(textBox1.Text);
/* Wat er gebeurd bij RadioButton1 Checked */
if (radioButton1.Checked)
{
number = aantalgroep * 8;
textBox2.Text = number.ToString();
if (aantalgroep < 10)
textBox2.Text = number.ToString();
}
}
Go in design editor, click on your textbox, click on little lighting, find TextChanged and click on arrow pointing down (next to TextChanged field). There you will have enlisted your already created method named button1_Click, select it and voila. Every time you change text in textbox you will call you method to auto calculate.
For sanity's sake, you should probably move the logic out of the click handler, since you plan to call it from various places. Once you have the logic extracted, you can call it from anywhere you want.
private void textBox1_TextChanged(object sender, EventArgs e)
{
Calculate();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
//You probably don't want to call Calculate here, due to infinite recursion
//Calculate();
}
private void button1_Click(object sender, EventArgs e)
{
Calculate();
}
private void Calculate()
{
aantalgroep = int.Parse(textBox1.Text);
/* Wat er gebeurd bij RadioButton1 Checked */
if (radioButton1.Checked) {
number = aantalgroep * 8;
textBox2.Text = number.ToString();
if (aantalgroep < 10) {
textBox2.Text = number.ToString();
}
}
}

How to add into a singular number when pressing different buttons

The title was properly written wrong but i will explain currently i have 2 sets of three buttons linked to a label. when i press a button it will place a number in the label as a result what i want to do is after the first button is pressed and then a second is clicked i want the two scores to add together to make a total result in the label eg if i press "three of a kind" which equals 3 points then press "four of a kind" which equals 6 points i want a result of 9 in the label and then if i press "five of a kind" which equals 12 point the label would then read 18 ect can i get any help please there isnt any code to put in due to not finding anything i will put in how my buttons are linked to my labels.
Result
public class Result
{
}
private void button2_Click(object sender, EventArgs e)
{
String add = (Convert.ToInt32(3)).ToString();
label6.Text = Convert.ToString(add);
}
private void button5_Click(object sender, EventArgs e)
{
String add = (Convert.ToInt32(3)).ToString();
label7.Text = Convert.ToString(add);
}
private void button3_Click(object sender, EventArgs e)
{
String add = (Convert.ToInt32(5)).ToString();
label6.Text = Convert.ToString(add);
}
private void button6_Click(object sender, EventArgs e)
{
String add = (Convert.ToInt32(5)).ToString();
label7.Text = Convert.ToString(add);
}
private void button4_Click(object sender, EventArgs e)
{
String add = (Convert.ToInt32(12)).ToString();
label6.Text = Convert.ToString(add);
}
private void button7_Click(object sender, EventArgs e)
{
String add = (Convert.ToInt32(12)).ToString();
label7.Text = Convert.ToString(add);
}
I didn't quite understand the question, but I would suggest you to read about WPF and the MVVM mechanism to sync the data between the UI and the data.
What you're doing is writing a lot of code-behind code that is duplicated over and over and is doing a lot of unnecessary work (you convert a number to Int, then convert the result to string and then convert it again to string)
This function can be used to do the work property and efficiently once:
private void UpdateLabelText(Label label, int number) {
label.Text = number.ToString();
}
And use this method whenever you need to update the text in your label.
You have to cast the value of label.Text to int then add the value and then recast to string:
private void button6_Click(object sender, EventArgs e)
{
AddToLabel(label7, 12);
}
void AddToLabel(Label label, int value)
{
var n = int.Parse(label.Text); // convert the actual value of label.Text to int
var add = n + value; // add the increment
label.Text = add.ToString(); // assign to label.Text
}

How to make buttons to enter specific values?

public partial class Form1 : Form
{
public static string a = "a"; public static string b = "b"; public static string c = "c";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = a;
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = b;
}
private void button3_Click(object sender, EventArgs e)
{
textBox1.Text = c;
}
private void button4_Click(object sender, EventArgs e)
{
a = null;
b = null;
c = null;
}
}
I want to make a simple keyboard for a chat.
I started it with a small sample program in which there are only 3 buttons; Button a, Button b, Button c for a,b,c, respectively.
When I run the Program,I press Button a for a & then Button b for b (Now I want the Output in the form ab) but it first shows a and then on pressing button b it erases a and shows b.
I want to make more buttons like these to make a keyboard.
Basically,I want to print the letters stored in the buttons sequentially,but it erases the first one and then prints the next one..
The easiest way to create an on-screen keyboard is to use the buttons texts, except in special keys like backspace, enter, clear etc`.
That way all your text buttons click events can be handled with a single method:
private void KeyButton_Click(object sender, EventArgs e)
{
textBox1.Text += ((Button)sender).Text;
}
private void ClearButton_Click(object sender, EventArgs e)
{
textBox1.Text = string.Empty;
}
private void BackspaceButton_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text.SubString(0, textBox1.Text.Length-1);
}
It erases the value because you are using = operator. Try to use +=
textBox1.Text += c;
textBox1.Text = textBox1.Text + c;
Also you can get a text value from the Button's Text property.
And have only one Button.Click event handler, for each button.
private void button_Click(object sender, EventArgs e)
{
var button = sender as Button;
textBox1.Text = textBox1 + button.Text;
}
As I told you in the comments before you posted the code you need to concatenate (a.k.a append) the character to the text box.
If you have a text box named textBox1 doing this:
textBox1.Text = 'a'
will replace any text already written in the text box with the character 'a'
What you need to do is use the += operator:
textBox1.Text += a;
textBox1.Text = b;
textBox1.Text = c;

Calculating Math in GUI

So I have a Calculator GUI with:
2 textboxes for user inputted numbers,
1 button for adding these numbers together,
and 1 textbox for showing the result
However, I cannot seem to be able to do the coding part of this, here is what I have:
public partial class Calculator : Form
{
public string firstOperand;
public string secondOperand;
public string result;
public Calculator()
{
InitializeComponent();
}
private void Calculator_Load(object sender, EventArgs e)
{
}
private void FirstOperandTextBox_TextChanged(object sender, EventArgs e)
{
FirstOperandTextBox.Text = firstOperand;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
SecondOperandTextBox.Text = secondOperand;
}
private void AddButton_Click(object sender, EventArgs e)
{
firstOperand + secondOperand = result;
}
For the addButton part, I am getting the error, "The left hand side of an assignment must be a variable, property, or indexer".
There are several problems with your code
You write your statements as you would write the equations in real life, ie 1 + 1 = 2. But in the code, you have to write it the other way around - you assign value to a variable, so you should have
result = firstOperand + secondOperand;
You try to add together string values. So if you had 1 and 1 in your operands, the result would be 11 and not 2 as you expect.
Assigning the value of the operands in the TextChanged event is unnecessary, and you can simply do the conversion in the buttons OnClick event.
Furthermore, since you only want numbers, and not text, you would be better off using NumericUpDown control, instead of TextBox. That will take care of wrong input for you (wrong input would be if user put some other characters in the TextBox, or empty value). If you use TextBox, you have to do some conversion from string first.
private void AddButton_Click(object sender, EventArgs e)
{
result = numericFirst.Value + numericSecond.Value;
}
Generally, for read only values, you would use Label and not TextBox, to show the result
private void AddButton_Click(object sender, EventArgs e)
{
result = numericFirst.Value + numericSecond.Value;
lblResult.Text = result.ToString();
}
In AddButton_Click, change firstOperand + secondOperand = result to firstOperand.Text + secondOperand.Text
You want your result to store the final value.
private void AddButton_Click(object sender, EventArgs e)
{
result = (Convert.ToInt32(firstOperand) + Convert.ToInt32(secondOperand)).ToString();
MyResultTextBox.Text=result;
}
private void AddButton_Click(object sender, EventArgs e)
{
int first = 0;
int second = 0;
//Use TryParse() method to avoid exceptions while parsing an invalid string
int.TryParse(FirstOperandTextBox.Text, out first);
int.TryParse(SecondOperandTextBox.Text, out second);
//in the left hand side of = operator, there **must** be a variable always.
result = first + second;
ResultTextBox.Text = result.ToString();
}

Categories