Calculate or Clear wont' work - c#

I am working on a Windows Form. Every time I press Calculate or clear, nothing happens. The form loads but buttons won't work. Textboxes remain clear, with no values. Visual Studio doesn't recognize the code as a mistake. Any help?
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
int numberOfInvoices = 0;
decimal totalOfInvoices = 0m;
decimal invoiceAverage = 0m;
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal txtSubtotal = Convert.ToDecimal(txtEnterSubtotal.Text);
decimal discountPercent = .25m;
if (txtSubtotal >= 500)
{
discountPercent = .2m;
}
else if (txtSubtotal >= 250 && txtSubtotal < 500)
{
discountPercent = .15m;
}
else if (txtSubtotal >= 100 && txtSubtotal < 250)
{
discountPercent = .1m;
}
else
{
discountPercent = .0m;
}
decimal discountAmount = Math.Round(txtSubtotal * discountPercent, 2);
decimal invoiceTotal = txtSubtotal - discountAmount;
this.txtSubtotal.Text = txtSubtotal.ToString("c");
txtDiscountPercent.Text = discountPercent.ToString("p1");
txtDiscountAmount.Text = discountAmount.ToString("c");
txtTotal.Text = invoiceTotal.ToString("c");
numberOfInvoices++;
totalOfInvoices += invoiceTotal;
invoiceAverage = totalOfInvoices / numberOfInvoices;
txtNumberOfInvoices.Text = numberOfInvoices.ToString();
txtTotalOfInvoices.Text = totalOfInvoices.ToString("c");
txtInvoiceAverage.Text = invoiceAverage.ToString("c");
txtEnterSubtotal.Text = "";
txtEnterSubtotal.Focus();
}
private void btnClearTotals_Click(object sender, System.EventArgs e)
{
numberOfInvoices = 0;
totalOfInvoices = 0m;
invoiceAverage = 0m;
txtNumberOfInvoices.Text = "";
txtTotalOfInvoices.Text = "";
txtInvoiceAverage.Text = "";
txtEnterSubtotal.Focus();
}
}
}
I really appreciate your help, please let me know how I could improve.

Both your click handlers seem to work fine. I am guessing you don't have them connected to the button objects for some reason. Maybe you created them, saved the Form1.cs file, and then opened the Form in designer and hit undo or something like that.
You should be able to make them work again by opening the form in designer, double-clicking the button and move the code to the new method created by the designer.
Once connected, the Form1.Designer.cs should contain the following line:
this.btnCalculate.Click += new System.EventHandler(this.btnCalculate_Click);
and similar for the clear button.

Related

How to make radiobuttons check themselves accordingly wth using a if else construction?

The following problem though I can not seem to solve by using google.
The program I am writing ask for an amount of shoes that are going to be purchased, then based on amount of shoes a discount is given, 0%, 15%, or 25%.
I have it all written so that the right price appears in a label, the only thing I need to do is make the according radiobutton check itself ( 0%, 15%, or 25%)
Can somebody tell me the syntax?
Code I have written thus far:
private void button1_Click(object sender, EventArgs e)
{
decimal schoenen1= 0;
schoenen1 = Convert.ToDecimal(textBox1.Text);
decimal prijs1 = schoenen1 * 100;
decimal prijs2 = schoenen1 * 85;
decimal prijs3 = schoenen1 * 75;
if (schoenen1 >5)
{
label3.Text = prijs3.ToString();
}
if (schoenen1 == 2)
{
label3.Text = prijs2.ToString();
}
if (schoenen1 >2)
{
label3.Text = prijs2.ToString();
}
if (schoenen1 == 1)
{
label3.Text = prijs1.ToString();
}
Since you want to assign the label only once, use if-else, otherwise e.g. when schoenen1 = 6 then case > 5 and case > 2 will both be executed.
private void button1_Click(object sender, EventArgs e)
{
decimal schoenen1 = Convert.ToDecimal(textBox1.Text);
decimal prijs1 = schoenen1 * 100;
decimal prijs2 = schoenen1 * 85;
decimal prijs3 = schoenen1 * 75;
if (schoenen1 > 5) {
label3.Text = prijs3.ToString();
radioButton1.Checked = true;
} else if (schoenen1 >= 2) {
label3.Text = prijs2.ToString();
radioButton2.Checked = true;
} else if (schoenen1 == 1) {
label3.Text = prijs1.ToString();
radioButton3.Checked = true;
}
}
Also, you can combine schoenen1 == 2 and schoenen1 > 2 into schoenen1 >= 2, since you are assigning the same value in both cases.
Alternatively, you can exit the method with return:
private void button1_Click(object sender, EventArgs e)
{
decimal schoenen1 = Convert.ToDecimal(textBox1.Text);
decimal prijs1 = schoenen1 * 100;
decimal prijs2 = schoenen1 * 85;
decimal prijs3 = schoenen1 * 75;
if (schoenen1 > 5) {
label3.Text = prijs3.ToString();
radioButton1.Checked = true;
return;
}
if (schoenen1 >= 2) {
label3.Text = prijs2.ToString();
radioButton2.Checked = true;
return;
}
if (schoenen1 == 1) {
label3.Text = prijs1.ToString();
radioButton3.Checked = true;
}
}
Yet another way is to use a switch statement:
switch (schoenen1)
{
case > 5:
label3.Text = prijs3.ToString();
radioButton1.Checked = true;
break;
case >= 2:
label3.Text = prijs2.ToString();
radioButton2.Checked = true;
break;
case 1:
label3.Text = prijs1.ToString();
radioButton3.Checked = true;
break;
}
See also: Selection statements - if, else and switch

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

Move data from one form textbox to another in c#

So I have an invoice total form that should calculate the percentage discount among other things. I'm adding a second form to the code that allows you to change the sales tax I got it to populate the form and actually work with no errors but I can't get it to move the data from the textbox on frmSalesTax to the txtSalesTax.Text in frmInvoiceTotal.
frmInvoiceTotal Code:
public frmInvoiceTotal()
{
InitializeComponent();
}
frmSalesTax percent = new frmSalesTax();
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal productTotal = Convert.ToDecimal(txtProductTotal.Text);
decimal salesTax = (7.75m/100m) * productTotal;
decimal discountPercent = .0m;
if (productTotal < 100)
discountPercent = .0m;
else if (productTotal >= 100 && productTotal < 250)
discountPercent = .1m;
else if (productTotal >= 250)
discountPercent = .25m;
decimal discountAmount = (productTotal + salesTax) * discountPercent;
decimal subtotal = productTotal - discountAmount;
decimal invoiceTotal = (subtotal + salesTax) - discountAmount;
txtSubtotal.Text = subtotal.ToString("c");
txtSalesTax.Text = salesTax.ToString("c");
txtDiscountPercent.Text = discountPercent.ToString("p1");
txtDiscountAmount.Text = discountAmount.ToString("c");
txtTotal.Text = invoiceTotal.ToString("c");
txtProductTotal.Focus();
}
private void btnChange_Click(object sender, EventArgs e)
{
percent.salesTax = txtSalesTax.Text;
switch (percent.ShowDialog())
{
case DialogResult.OK:
txtSalesTax.Text = percent.salesTax;
break;
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
invoiceTotal GUI:
frmSalesTax Code:
public partial class frmSalesTax : Form
{
public string salesTax
{
get;
set;
}
public frmSalesTax()
{
InitializeComponent();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnOk_Click(object sender, EventArgs e)
{
this.salesTax = txtPercent.Text;
txtPercent.Text = "";
Hide();
}
I know I'm missing something but I can't figure out what it is.
salesTax GUI:
You've got the right idea making a property on frmSalesTax to communicate...but you're not really using it.
In your frmInvoiceTotal, you need to send the current value to frmSalesTax.salesTax and then handle the results of the percent dialog returning DialogResult.OK:
private void btnChange_Click(object sender, EventArgs e)
{
percent.salesTax = txtSalesTax.Text; //--> send current value to frmSalesTax
switch ( percent.ShowDialog() ) //--> ShowDialog will return the DialogResult of the pressed button
{
case DialogResult.OK:
txtSalesTax.Text = percent.salesTax; //--> update with new value from frmSalesTax
break;
}
}
...and, in your frmSalesTax, you need to put the txtPercent.Text into the salesTax property when the user clicks the OK button:
private void btnOk_Click(object sender, EventArgs e)
{
this.salesTax = txtPercent.Text; //--> frmInvoiceTotal will read this after the OK button is clicked
txtPercent.Text = "";
Hide();
}
Important: you have to make sure the frmSalesTax buttons have their DialogResult set, so that frmInvoiceTotal.btnOk_Click knows that it's okay to get the value:
Edit
The property (in frmSalesTax) needs to not be based on the form's text values...because you're setting that to "" when the form hides. This is what you want for the property:
public string salesTax
{
get;
set;
}
This would go with the other changes I mentioned earlier.
Edit 2
It's easy to get frustrated. There are a lot of moving pieces, and I can understand how the eyes can cross. Here's the crux of the issue - your calculation is trashing things on you;-)
These lines in the btnCalculate_Click:
decimal salesTax = (7.75m/100m) * productTotal;
decimal discountPercent = .0m;
//...
txtSalesTax.Text = salesTax.ToString("c");
txtDiscountPercent.Text = discountPercent.ToString("p1");
...should be the initial values and come in the form's initialization code:
public frmInvoiceTotal()
{
InitializeComponent();
decimal salesTax = (7.75m/100m) * productTotal;
decimal discountPercent = .0m;
txtSalesTax.Text = salesTax.ToString("c"); //--> the initial value
txtDiscountPercent.Text = discountPercent.ToString("p1");
}
...and then, the calculation should not re-populate txtSalesTax.Text or txtDiscountPercent.Text. The txtSalesTax.Text might be update from showing frmSalesTax, and I'm guessing you're gonna make another form to override discount percent at some point.
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal productTotal = Convert.ToDecimal(txtProductTotal.Text);
decimal salesTax = Convert.ToDecimal(salesTax.Text) * productTotal; //--> if it got changed in frmSalesTax
decimal discountPercent = .0m;
if (productTotal < 100)
discountPercent = .0m;
else if (productTotal >= 100 && productTotal < 250)
discountPercent = .1m;
else if (productTotal >= 250)
discountPercent = .25m;
decimal discountAmount = (productTotal + salesTax) * discountPercent;
decimal subtotal = productTotal - discountAmount;
decimal invoiceTotal = (subtotal + salesTax) - discountAmount;
txtSubtotal.Text = subtotal.ToString("c");
//txtSalesTax.Text = salesTax.ToString("c"); //--> don't do this...it steps on what came from frmSalesTax
//txtDiscountPercent.Text = discountPercent.ToString("p1"); //--> when you add another form to override this
txtDiscountAmount.Text = discountAmount.ToString("c");
txtTotal.Text = invoiceTotal.ToString("c");
txtProductTotal.Focus();
}
I bet this get you a lot closer :-)

increment how many times an image is displayed in a picturebox

I'm trying to display an image using a button click and increment a variable when a certain image is shown, but with the code below the variable num is always 0.
my code
int num = 0;
int i = 0;
int x = 0;
PictureBox[] pictureBoxs = new PictureBox[4];
Random rnd = new Random();
public UserControl1()
{
InitializeComponent();
pictureBoxs[0] = pbimg1;
pictureBoxs[1] = pbimg2;
pictureBoxs[2] = pbimg3;
pictureBoxs[3] = pbimg4;
x = rnd.Next(2);
}
public void displaypics()
{
pictureBoxs[i].Image = imageList1.Images[x];
}
private void btn2_Click(object sender, EventArgs e)
{
i=1;
displaypics();
if (pictureBoxs[i].Image == imageList1.Images[1])
{
num++;
}
if (num == 2)
{
tb1.Visible = true;
tb1.Text = "GAME OVER!" + num;
}
}
The reason is most likely that num is being instantiated to zero everytime the class is being instantiated
What happens when you set breakpoints and step through the code? Is the int set as 0, or does it contain the updated value?
I'm not sure what the context is in which that piece of code is used. So I guess what should solve this would be adding x = rnd.Next(2) to the btn2_Click method. Making it look like this:
private void btn2_Click(object sender, EventArgs e)
{
x = rnd.Next(2);
displaypics();
if (pictureBoxs[i].Image == imageList1.Images[1])
{
num++;
}
if (num == 2)
{
tb1.Visible = true;
tb1.Text = "GAME OVER!" + num;
}
i++;
}
Maybe you could give some more details on what that control should do/how it's used.

C# Calculator with memory buttons

I am having some difficulties making my calculator have the ability to store values. The calculator works for everything except this and I am quite stuck. I think I might have to declare some constants or something that I am missing right now. I am super new at this and appreciate the help. Here is my code. Thanks for any help guys. Right now I am getting no errors but nothing works either! I am also supposed to make it so a "M" appears in a textbox when there is a value stored in memory but I figured it was easier to start with this part.
private void digitCalculate_Click(object sender, EventArgs e)
{
Button ButtonThatWasPushed = (Button)sender;
string ButtonText = ButtonThatWasPushed.Text;
decimal EndResult = 0;
decimal MemoryStore = 0;
if (ButtonText == "MC")
{
//Memory Clear
MemoryStore = 0;
return;
}
if (ButtonText == "MR")
{
//Memory Recall
txtDisplay.Text = MemoryStore.ToString();
return;
}
if (ButtonText == "MS")
{
// Memory subtract
MemoryStore -= EndResult;
return;
}
if (ButtonText == "M+")
{
// Memory add
MemoryStore += EndResult;
return;
}
}
You need to have Form level variable for decimal MemoryStore = 0; , since you have function level variable it will initialized to 0 when you click on digitCalculate button
decimal MemoryStore = 0;
decimal EndResult = 0;
public Form1()
{
InitializeComponent();
}
private void digitCalculate_Click(object sender, EventArgs e)
{
Button ButtonThatWasPushed = (Button)sender;
string ButtonText = ButtonThatWasPushed.Text;
//decimal EndResult = 0;
//decimal MemoryStore = 0;
And also note that
MC = Memory Clear sets the memory to 0
MR = Memory Recall uses the
number in memory
MS = Memory Store puts the number on the display into the memory
You nee to change "MS" logic and add "M-"
if (ButtonText == "MS")
{
MemoryStore = Decimal.Parse(txtDisplay.Text);
return;
}
if (ButtonText == "M-")
{
// Memory subtract
MemoryStore -= EndResult;
txtDisplay.Text = MemoryStore.ToString();
return;
}
if (ButtonText == "M+")
{
// Memory add
MemoryStore += EndResult;
txtDisplay.Text = MemoryStore.ToString();
return;
}
Just change the variable MemoryStore to a global variable. At the moment, it is being re-declared each time a button is pushed, meaning that the data is lost between button presses. Move it outside of the function, and it should work fine.

Categories