Creating decreasing sequence with (x++)%n in C# - c#

So, I know that with a code snippet such as:
int x = 0; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += (x++)%4 + 1;
}
a sequence of 12341234 is displayed on the form if the button is clicked 8 times.
My goal is to get 43214321 to display.
I'm able to get 32103210 with:
int x = 0; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += 3-(x++)%4;
}
I'm also able to get 32143214 with:
int x = 1; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += 4-(x++)%4 + ;
}
What am I doing wrong? And is there a general formula for this?
Note: My x DOES have to be initialized to 1.

Just change the formula to:
Label1.Text += 4-((x-1)++)%4;

Try using this formula:
5-(1+(x+++3)%4)
That is:
Label1.Text += (5-(1+(x+++3)%4)).ToString();

The first line of code that you've written is basically cycling between 3 to 1.
x=0;
Label1.Text += 3-(x++)%4;
x=0 || Output=3.
Label1.Text= 0+3-(0%4)=3
x=1 || Output=2.
Label1.Text= 0+3-(1%4)=2
x=2 || Output=1.
(Dry run as done above)
x=3 || Output=0.
(dry run as done above)
x=4 and the cycle repeats.
You could dry run your second line of code to understand why your answer comes the way it does, but to answer your question in concise:
int x = 0; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += 4-(x++)%4;
}

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

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();
}
}
}

Timer on Mouse Down in c#

So I want to know for how long the user presses down on a button. I am using the button1_MouseDown method as you can see below. However the count variable is staying 0.
Can someone please help me solve this problem please?
Thanks in advance!
private void button1_MouseDown(object sender, MouseEventArgs e)
{
foreach(MusKey mk in this.Controls)
{
if(sender == mk)
{
if(e.Button == MouseButtons.Left)
{
timer1.Enabled = true;
count = 0;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
sp.SoundLocation = ( ---directory---- + mk.musicNote + ".wav");
sp.Play();
}
}
}
}
private void timer1_Tick (object sender, EventArgs e)
{
count = count++;
}
Your problem is due to the assignment using a post increment.
count = count++;
The order of events is to evaluate the right hand side including side effects before the assignment - so the current value of count is stored (=0) count is then incremented & now the stored value is assigned - the original value of zero is being written back over the incremented value.
You only need to use count++;
private void timer1_Tick (object sender, EventArgs e)
{
count++;
}

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();
}

Add to int each time a button is clicked and show in textbox c#

I am very new to programming and I am trying to do that every time you click a button, it adds one to the value of an int and shows it in a textbox. My code is:
private void button1_Click(object sender, EventArgs e)
{
int a = 100;
a++;
txtBox1.Text = a.ToString();
}
So when I click the button it shows in the text box 101, but when I click it again, I want the textbox to show 102 and 103 etc etc. Any ideas? I assume it's very easy and using some variation of a loop but I have tried a few things and nothing seems to work. Any tips would be greatly appreciated! Thanks.
You have to store your value outside of Method Body.
private int a = 100;
private void button1_Click(object sender, EventArgs e)
{
a++;
txtBox1.Text = a.ToString();
}
What you did in your program is anytime you clicked the button, new Integer a was declared with value of 100, then you are increasing it by 1 and that's why you always seen '101'.
In your code you delcare a and assign a value to it over and over again every time you click on the button.
You should declare the variable outside of button1_Click method:
class Window1
{
int a = 100;
....
private void button1_Click(object sender, EventArgs e)
{
a++;
txtBox1.Text = a.ToString();
}
}
You need to declare a as a member of the class containing your method:
private int _a = 100;
private void button1_Click(object sender, EventArgs e)
{
_a++;
txtBox1.Text = _a.ToString();
}
If you don't do that, you will have a new instance every time the button is clicked, so you will always see 101 in your text box.
It is possible not to create global fields and store count of clicks inside the textbox.
This is especially convenient if you have several buttons.
private void button1_Click(object sender, EventArgs e)
{
if (txtBox1.Tag is int)
{
int a = (int)txtBox1.Tag;
a++;
txtBox1.Tag = a;
txtBox1.Text = a.ToString();
}
else
{
txtBox1.Tag = 100;
txtBox1.Text = 100;
}
}
int a = 100;
txtBox1.Text = a.ToString();
......
private void button1_Click(object sender, EventArgs e)
{
a++;
txtBox1.Text = a.ToString();
}
Placing int a = 100; inside the button1_Click(object sender, EventArgs e) will set a to 100 when each time function executing. If you need to have a counter place it outside from the function(Then it will initialize only once.) and increment it when executing the function.
Solution
int a = 100;
private void button1_Click(object sender, EventArgs e)
{
a++;
txtBox1.Text = a.ToString();
}
static int a = 100;
private void button1_Click(object sender, EventArgs e)
{
a++;
txtBox1.Text = a.ToString();
}
if you want to optimization your code than firstly set the textbox property text = 100 and write only one line code in button click event
private void button1_Click(object sender, EventArgs e)
{
txtBox1.Text = (Convert.ToInt32(txtBox1.Text) + 1).ToString();
}
as you know C# complie the code line by line and you have only one line code than it's give faster perfomance.

Categories