I have a problem regarding to payment button.
I don't encounter an error before building, but after building and clicking the payment button it hangs. I think its because of lblTotalPrice.text, but I don't know how to fix it.
public partial class Form1 : Form
{
int totalCost;
public double holDer;
public Form1()
{
InitializeComponent();
this.cbo1.Items.AddRange(new object[] { "Lechon Kawali - 200", "Bicol Express - 300"
,"Adobo - 350" });
}
private void btnAdd_Click(object sender, EventArgs e)
{
lb1.Items.Add(cbo1.SelectedItem);
lb1.SelectedIndex = lb1.SelectedIndex ;
int z = 0;
if (cbo1.SelectedIndex == 0)
{
z = z + 1;
}
if (cbo1.SelectedIndex == 1)
{
z = z + 2;
}
if (cbo1.SelectedIndex == 2)
{
z = z + 3;
}
switch(z)
{
case 1:
totalCost = totalCost + 200;
break;
case 2:
totalCost = totalCost + 300;
break;
case 3:
totalCost = totalCost + 350;
break;
}
lblSubTotalCost.Text = ("Php " + totalCost.ToString());
}
private void btnDelete_Click(object sender, EventArgs e)
{
int deleteCost = 0;
int itemCost = 0;
foreach (int selectedIndex in lb1.SelectedIndices)
{
itemCost = int.Parse(lb1.Items[selectedIndex].ToString().Split('-')[1]);
deleteCost += itemCost; lb1.Items.RemoveAt(selectedIndex);
}
totalCost = totalCost - deleteCost;
lblSubTotalCost.Text = ("Php " + totalCost.ToString());
lb1.Items.Remove(lb1.SelectedItem);
if (lb1.Items.Count > 0)
{
lb1.SelectedIndex = 0;
}
else
MessageBox.Show("No orders");
}
private void lblVAT_TextChanged(object sender, EventArgs e)
{
Add();
}
private void lblSubTotalCost_TextChanged(object sender, EventArgs e)
{
multiply();
Add();
}
public void multiply()
{
int a;
double b = 0.12;
bool Valid = int.TryParse(totalCost.ToString(), out a);
if (Valid)
lblVAT.Text = (a * b).ToString();
else
lblVAT.Text = "No VAT entered";
}
private void lbTotalPrice_TextChanged(object sender, EventArgs e)
{
Add();
}
public void Add()
{
int a;
int b;
bool AValid = int.TryParse(totalCost.ToString(), out a);
bool BValid = int.TryParse(lblVAT.Text, out b);
if (AValid && BValid)
{
lblTotalPrice.Text = ("Php " + (a + b).ToString());
}
}
private void btnPayment_Click(object sender, EventArgs e)
{
holDer = double.Parse(tbPayment.Text) - double.Parse(lblTotalPrice.Text);
MessageBox.Show("Change: " + holDer.ToString());
}
}
As you stated in your comments, your problem it is not that your application hangs, but the problem is that you are getting a Input string was not in a correct format Exception.
That it seems is from this block:
private void btnPayment_Click(object sender, EventArgs e)
{
holDer = double.Parse(tbPayment.Text) - double.Parse(lblTotalPrice.Text);
MessageBox.Show("Change: " + holDer.ToString());
}
As it is a not very complex code, your problem seems to be when you are casting your textboxes to Double. Be sure that you are using the correct separator for double values and that you not have any strange characters in tbPayment
Try using TryParse method:
double res;
if(double.TryParse(tbPayment.Text, out res))
{
holDer = res - double.Parse(lblTotalPrice.Text);
MessageBox.Show("Change: " + holDer.ToString());
}
else
{
MessageBox.Show("Input a correct format");
}
I suspect it's because the lblTotalPrice_TextChanged event-handler calls Add() which then changes the lblTotalPrice.Text property, causing the event to fire again, ad -infinitum?
Related
I have 3 list boxes, the listBox_menu is where the items are first displayed if buttons (entrees, drinks, and sides) are clicked, then to add the items to order you select your item from the listBox_menu and click add to order to have it appear in the listBox_order. From there once the customer order is ready to be made the submit button will print out the customers name (textBox_name) and all the items in the listBox_order, and display it all in one line.
I'm just having trouble figuring out how to do that, if anyone could please help.
First define two global variables, then use the CalculateTotalCost function (which I defined).
My answer has been updated.
Output (tested in Visual Studio 2017, .Net Framework 4.5.2):
These are my codes:
public Form1()
{
InitializeComponent();
listBox_menu.SelectionMode = SelectionMode.MultiExtended;
}
double Cost = 0;
string Order = null;
public double CalculateTotalCost(object input, bool Total)
{
if (Total == true)
{
switch (input)
{
case "Salad":
Cost += 2500;
break;
case "Rice":
Cost += 3000;
break;
case "non-alcoholic beer":
Cost += 1000;
break;
case "Water":
Cost += 200;
break;
case "Ex1":
Cost += 2200;
break;
default:
Cost += 2200;
break;
}
}
else
{
switch (input)
{
case "Salad":
Cost -= 2500;
break;
case "Rice":
Cost -= 3000;
break;
case "non-alcoholic beer":
Cost -= 1000;
break;
case "Water":
Cost -= 200;
break;
case "Ex1":
Cost -= 2200;
break;
default:
Cost -= 2200;
break;
}
}
return Cost;
}
private void Entrees_Click(object sender, EventArgs e)
{
listBox_menu.Items.Clear();
listBox_menu.Items.Add("Salad");
listBox_menu.Items.Add("Rice");
}
private void Drinks_Click(object sender, EventArgs e)
{
listBox_menu.Items.Clear();
listBox_menu.Items.Add("non-alcoholic beer");
listBox_menu.Items.Add("Water");
}
private void Sides_Click(object sender, EventArgs e)
{
listBox_menu.Items.Clear();
listBox_menu.Items.Add("Ex1");
listBox_menu.Items.Add("Ex2");
}
private void AddtoOrder_Click(object sender, EventArgs e)
{
if(listBox_menu.SelectedItems.Count>0)
{
for (int i = 0; i < listBox_menu.SelectedItems.Count; i++)
{
listBox_order.Items.Add(listBox_menu.SelectedItems[i].ToString());
lblTotalCost.Text = (CalculateTotalCost(listBox_menu.SelectedItems[i].ToString(),true)).ToString();
}
}
}
private void RemoveFromOrder_Click(object sender, EventArgs e)
{
if (listBox_order.SelectedItems.Count > 0)
{
listBox_order.Items.Remove(listBox_order.SelectedItem);
}
Order = null;
for (int i = 0; i < listBox_order.Items.Count; i++)
{
Order += listBox_order.Items[i].ToString() + " , ";
}
Cost = 0;
if (listBox_order.Items.Count > 0)
{
for (int i = 0; i < listBox_order.Items.Count; i++)
{
Cost = (CalculateTotalCost(listBox_order.Items[i], true));
}
}
lblTotalCost.Text = Cost.ToString();
}
private void Submit_Click(object sender, EventArgs e)
{
MessageBox.Show("Customer name: " + txtBoxCustomerName.Text + " Orders: " + Order + " Total cost: " + Cost);
}
Hello I'm still new to programming and yes this is not the best code you will see... I tried making calculator on C# windows form for fun and I'm having trouble on the subtraction and division operations, but the addition and multiplication works perfectly fine for me. I decided to have a list array so that I would be able to input numbers as much as I want.
The error for the subtraction is when I input for example 5 - 2 the result will be -3
As for the division the error is that the result is always 1
Please tell me where did I go wrong and give a detailed explanation if possible so that I would understand more about programming. Thanks in advance!
namespace CalculatorTestForm1
{
public partial class Form1 : Form
{
public static List<int> Numlist = new List<int>();
public static string operation;
public Form1()
{
InitializeComponent();
}
private void Button_Click(object sender, EventArgs e)
{
Button Num = (Button)sender;
TXTBox.Text += Num.Text;
}
private void BPlus_Click(object sender, EventArgs e)
{
operation = "add";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BEquals_Click(object sender, EventArgs e)
{
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
int sum = 0;
int product = 1;
int quotient = 1;
int difference = 0;
if (operation == "add"){
foreach (int value in Numlist)
{
sum += value;
}
string Answer = sum.ToString();
TXTBox.Text = Answer;
}else if(operation == "minus"){
foreach (int value in Numlist)
{
difference = value - difference;
}
string Answer = difference.ToString();
TXTBox.Text = Answer;
}
else if (operation == "multiply")
{
foreach (int value in Numlist)
{
product *= value;
}
string Answer = product.ToString();
TXTBox.Text = Answer;
}
else if (operation == "divide")
{
foreach (int value in Numlist)
{
quotient = value / value;
}
string Answer = quotient.ToString();
TXTBox.Text = Answer;
}
Numlist.Clear();
}
private void BClear_Click(object sender, EventArgs e)
{
TXTBox.Text = "";
Numlist.Clear();
}
private void BMinus_Click(object sender, EventArgs e)
{
operation = "minus";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BDivide_Click(object sender, EventArgs e)
{
operation = "divide";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BMulti_Click(object sender, EventArgs e)
{
operation = "multiply";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
}
}
For the division it's obvious:
quotient = value / value;
value/value will always be 1.
There must be quotient in that loop somewhere...
For the subtraction the problem is that because of the way you do it, the order of the numbers are reversed.
lets say 5 - 2:
foreach (int value in Numlist)
{
difference = value - difference;
}
NumList = {5,2}
1st iteration:
difference = value(5) - difference(0) = 5
2nd iteration:
difference = value(2) - difference(5) = -3
You should reverse the order of the loop: NumList.Reverse()
And for the division as well:
Division:
foreach (int value in Numlist.Reverse())
{
quotient = value / quotient;
}
Subtraction:
foreach (int value in Numlist)
{
difference = value - difference;
}
I am working on a project in c# visual studio in which i am attempting to make a bowling calculator. i have made a class for frames which contains a throw1 and throw2. I first fill the array of classes with one button and calculate score after game completion. when i go to calculate score it tells me i have null values.below is my form code the class is just
class frames
{
public int intThrow1;
public int intThrow2;
}
the main form is
public partial class Form1 : Form
{
frames[] frame = new frames[11];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
int intFrst = int.Parse(textBox1.Text);
int intScnd = int.Parse(textBox2.Text);
if (lbxScorecard.Items.Count <= 21)
{
int intIndx = 0;
if (intFrst == 10)
{
frame[intIndx] = new frames();
frame[intIndx].intThrow1 = intFrst;
frame[intIndx].intThrow2 = 0;
lbxScorecard.Items.Add(frame[intIndx].intThrow1);
lbxScorecard.Items.Add(frame[intIndx].intThrow2);
intIndx += 2;
}
else
{
frame[intIndx] = new frames();
frame[intIndx].intThrow1 = intFrst;
frame[intIndx].intThrow2 = intScnd;
lbxScorecard.Items.Add(frame[intIndx].intThrow1);
lbxScorecard.Items.Add(frame[intIndx].intThrow2);
intIndx++;
}
}
else
{
MessageBox.Show("max throws");
}
}
private void button2_Click(object sender, EventArgs e)
{
int intScore = 0;
for (int index = 0; index <= 11; index++)
{
if (frame[index].intThrow1 == 10 && index < 9) // here is where it throws a null exception stating the index may be empty
{
if (frame[index + 1].intThrow1 != 10)
{
intScore = intScore + frame[index].intThrow1 + frame[index + 1].intThrow1 + frame[index + 1].intThrow2;
}
else if (frame[index].intThrow1 == 10)
{
intScore = intScore + frame[index].intThrow1 + frame[index + 1].intThrow1 + frame[index + 2].intThrow1;
}
}
else if (frame[index].intThrow1 + frame[index].intThrow2 == 10 && index < 9) //it was throwing the same exception here until i added && index<9 in the if statements.
{
intScore = intScore + frame[index].intThrow1 + frame[index].intThrow2 + frame[index + 1].intThrow1;
}
else
{
intScore = intScore + frame[index].intThrow1 + frame[index].intThrow2;
}
}
MessageBox.Show(intScore.ToString());
}
}
Problem is:
frames[] frame = new frames[11];
You also need to instantiate each element of the array like you did in the button1_Click function:
frame[intIndx] = new frames();
Also note that you have a class variable frame and the same one in button2_Click which is probably a bad idea.
I'm trying to make a program that generates 2 random numbers, then, after the user inputs the multiplication of those numbers, it will tell the user in a MessageBox whether or not the user was right or wrong. Sort of like an educational simulator.
I'm having problems with the end part. What I'm saying is; If the answer is the same as number1 and number2 multiplied, then it says; "Rétt!" and if not; "Rangt..."
Any ideas?
private void bt_end_Click(object sender, RoutedEventArgs e)
{
int number1 = 0;
int number2 = 0;
int answer = 0;
tbnumber1.Text = number1.ToString();
tbnumber2.Text = number2.ToString();
if (svar == (number1 * number2))
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt...");
}
}
}
}
The full code.
public MainWindow()
{
InitializeComponent();
}
int tala1 = 0;
int tala2 = 0;
int svar = 0;
private void btstart_Click(object sender, RoutedEventArgs e)
{
tbtala1.Text = "";
tbtala2.Text = "";
tbsvar.Text = "";
Random random = new Random();
tala1 = random.Next(1, 11);
tala2 = random.Next(1, 11);
tbtala1.Text = tala1.ToString();
tbtala2.Text = tala2.ToString();
}
private void btend_Click(object sender, RoutedEventArgs e)
{
tbtala1.Text = tala1.ToString();
tbtala2.Text = tala2.ToString();
tbsvar.Text = svar.ToString();
if (svar == (tala1 * tala2).ToString())
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt... :(");
}
}
}
}
SOLVED. Thank you to everyone who did/tried to help.
Final Version:
Final Version:
public MainWindow()
{
InitializeComponent();
}
int tala1 = 0;
int tala2 = 0;
int svar = 0;
private void btstart_Click(object sender, RoutedEventArgs e)
{
tbtala1.Text = "";
tbtala2.Text = "";
tbsvar.Text = "";
Random random = new Random();
tala1 = random.Next(1, 11);
tala2 = random.Next(1, 11);
tbtala1.Text = tala1.ToString();
tbtala2.Text = tala2.ToString();
}
private void btend_Click(object sender, RoutedEventArgs e)
{
tala1 = Convert.ToInt32(tbtala1.Text);
tala2 = Convert.ToInt32(tbtala2.Text);
svar = Convert.ToInt32(tbsvar.Text);
if (svar == (tala1 * tala2))
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt... :(");
}
To do this in a safe manner, you should not only Parse the text inputs to numbers, but you should also ensure that the text does in fact contain numbers first. If your numbers are supposed to be integers then you could use this:
private void bt_end_Click(object sender, RoutedEventArgs e)
{
int number1 = 0;
int number2 = 0;
if (int.TryParse(tbnumber1.Text, out number1) ||
int.TryParse(tbnumber12.Text, out number2)) MessageBox.Show("Rangt...");
MessageBox.Show(svar == number1 * number2 ? "Rétt!" : "Rangt...");
}
You're putting the numbers in the textbox values. you have to convert textbox values to numbers.
private void btend_Click(object sender, RoutedEventArgs e)
{
try{
tala1 = Convert.ToInt32(tbtala1.Text);
tala2 = Convert.ToInt32(tbtala2.Text);
svar = Convert.ToInt32(tbsvar.Text);
if (svar == (tala1 * tala2))
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt... :(");
}
}catch{
MessageBox.Show("Invalid input");
}
}
You never define svar. You probably meant something like this, assuming svar was set earlier and is the correct product of the random multiplication:
private void bt_end_Click(object sender, RoutedEventArgs e)
{
int number1 = 0;
int number2 = 0;
number1 = int.Parse(tbnumber1.Text);
number2 = int.Parse(tbnumber2.Text);
if (svar == (number1 * number2))
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt...");
}
}
1.I observed that you have not initialized variable 'svar' anywhere.
Initialise your svar variable with proper value.
2.Replace This :
if (svar == (number1 * number2).ToString())
With Following :
if (svar == (number1 * number2))
I'm new to C# so still finding my way around.
I have a button I want to enable only when a user enter text to textbox.
I get this error - "Object reference not set to an instance of an object".
Here is the related code (without the using and variables):
public MainWindow()
{
MessageBox.Show("Make sure to edit Settings tab.");
InitializeComponent();
if (startTextBox.Text == "0") // Checks to see if a textbox has some text other than zero. if no than the user cannot press button1 yet.
{
button1.IsEnabled = false;
}
else
{
button1.IsEnabled = true;
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (radioButton1.IsChecked == false)
{
label17.Content = "No Hourly wage was set.";
}
}
private void add(object sender, RoutedEventArgs e) /// here is a very long method so I've removed its content.
}
public void printTime()
{
int Sum = (this.EndInt - this.StartInt);
int Money = (Sum * this.L1001);
label16.Content = Sum;
label17.Content = Money;
if ((textBox1.Text == "0") && ((textBox2.Text == "0") || (textBox3.Text == "0")))
{
label17.Content = "No Hourly wage was set.";
}
}
public void printTime2()
{
int Sum = (this.EndInt - this.StartInt);
MessageBox.Show("Is it possible that you've worked - " + Sum + " Hours?");
}
public void printTime3()
{
int Sum = (this.EndInt - this.StartInt);
int Money = (Sum * this.L1001);
label16.Content = Sum;
label17.Content = Money;
if (textBox1.Text == "0")
{
label17.Content = "No Hourly wage was set.";
}
}
public int Convert(String S)
{
int i = int.Parse(S);
return i;
}
// Input Validation For Excepting Integers Only!
private void input(object sender, TextCompositionEventArgs e)
{ CheckIsNumeric(e); }
private void CheckIsNumeric(TextCompositionEventArgs e)
{
int result; if (!(int.TryParse(e.Text, out result) || e.Text == "."))
{ e.Handled = true; MessageBox.Show("Numbers Only"); }
}
private void startTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
button1.IsEnabled = true;
}
}
}
It's the scope problem. You didn't show where button1 is defined. But inside your event handler startTextBox_TextChanged, button1 definition is nowhere to be found (actually it needs to be instantiated as well). Since you try to invoke a method on an object (button1) which has not been instantiated yet, that exception was thrown.
If you post more than just those snippets, either I or someone else might be able to further help you.