it's my first post here. I'm learning C# (visual studio) at the moment and we have been building a program through given tasks. The last task is to create an "undo" button. This is the code so far:
namespace GestBar_v1._0
{
public partial class Form1 : Form
{
string[] bebidas = { "Café", "Ice Tea", "Água", "Aguardente" };
double[] precoBebidas = { 0.8, 1.5, 1.0, 1.0 };
string[] alimentacao = { "Bolos", "Sandes Mistas", "Torrada", "Salgados" };
double[] precoAlimentacao = { 1.0, 1.5, 1.5, 1.0 };
double soma = 0;
double fecho = 0;
void resetTxt()
{
txtPreco.BackColor = Color.White;
txtPreco.ForeColor = Color.Black;
txtPreco.Font = new Font("Microsoft Sans Serif", 11, FontStyle.Regular);
label2.Text = "Preço Final";
}
private void Processo(string[] items, double[] prices, int itemIndex)
{
if (listaProduto.Items.Contains(items[itemIndex]))
{
int index = listaProduto.Items.IndexOf(items[itemIndex]);
double count = double.Parse(listaUnidade.Items[index].ToString());
listaPreco.Items[index] = Math.Round(prices[itemIndex] * (count + 1), 2);
listaUnidade.Items[index] = count + 1;
soma += prices[itemIndex];
}
else
{
listaProduto.Items.Add(items[itemIndex]);
listaPreco.Items.Add(prices[itemIndex]);
listaUnidade.Items.Add(1);
soma += prices[itemIndex];
}
txtPreco.Text = soma.ToString();
}
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
resetTxt();
btn11.Visible = true;
btn12.Visible = true;
btn13.Visible = true;
btn14.Visible = true;
btn11.Text = bebidas[0] + "\n" + precoBebidas[0] + "€";
btn12.Text = bebidas[1] + "\n" + precoBebidas[1] + "€";
btn13.Text = bebidas[2] + "\n" + precoBebidas[2] + "€";
btn14.Text = bebidas[3] + "\n" + precoBebidas[3] + "€";
btn21.Visible = false;
btn22.Visible = false;
btn23.Visible = false;
btn24.Visible = false;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnAliment_Click(object sender, EventArgs e)
{
resetTxt();
btn21.Visible = true;
btn22.Visible = true;
btn23.Visible = true;
btn24.Visible = true;
btn21.Text = alimentacao[0] + "\n" + precoAlimentacao[0] + "€";
btn22.Text = alimentacao[1] + "\n" + precoAlimentacao[1] + "€";
btn23.Text = alimentacao[2] + "\n" + precoAlimentacao[2] + "€";
btn24.Text = alimentacao[3] + "\n" + precoAlimentacao[3] + "€";
btn11.Visible = false;
btn12.Visible = false;
btn13.Visible = false;
btn14.Visible = false;
}
private void btnTodosP_Click(object sender, EventArgs e)
{
resetTxt();
btn11.Visible = true;
btn12.Visible = true;
btn13.Visible = true;
btn14.Visible = true;
btn21.Visible = true;
btn22.Visible = true;
btn23.Visible = true;
btn24.Visible = true;
btn11.Text = bebidas[0] + "\n" + precoBebidas[0] + "€";
btn12.Text = bebidas[1] + "\n" + precoBebidas[1] + "€";
btn13.Text = bebidas[2] + "\n" + precoBebidas[2] + "€";
btn14.Text = bebidas[3] + "\n" + precoBebidas[3] + "€";
btn21.Text = alimentacao[0] + "\n" + precoAlimentacao[0] + "€";
btn22.Text = alimentacao[1] + "\n" + precoAlimentacao[1] + "€";
btn23.Text = alimentacao[2] + "\n" + precoAlimentacao[2] + "€";
btn24.Text = alimentacao[3] + "\n" + precoAlimentacao[3] + "€";
}
private void btn11_Click(object sender, EventArgs e)
{
resetTxt();
Processo(bebidas, precoBebidas, 0);
}
private void btn12_Click(object sender, EventArgs e)
{
resetTxt();
Processo(bebidas, precoBebidas, 1);
}
private void btn13_Click(object sender, EventArgs e)
{
resetTxt();
Processo(bebidas, precoBebidas, 2);
}
private void btn14_Click(object sender, EventArgs e)
{
resetTxt();
Processo(bebidas, precoBebidas, 3);
}
private void btn21_Click(object sender, EventArgs e)
{
resetTxt();
Processo(alimentacao, precoAlimentacao, 0);
}
private void btn22_Click(object sender, EventArgs e)
{
resetTxt();
Processo(alimentacao, precoAlimentacao, 1);
}
private void btn23_Click(object sender, EventArgs e)
{
resetTxt();
Processo(alimentacao, precoAlimentacao, 2);
}
private void btn24_Click(object sender, EventArgs e)
{
resetTxt();
Processo(alimentacao, precoAlimentacao, 3);
}
private void btnNovo_Click(object sender, EventArgs e)
{
resetTxt();
fecho += Convert.ToDouble(txtPreco.Text);
listaProduto.Items.Clear();
listaPreco.Items.Clear();
listaUnidade.Items.Clear();
txtPreco.Clear();
soma = 0;
}
private void btnRetirarSelec_Click(object sender, EventArgs e)
{
if (listaProduto.SelectedIndex >= 0)
{
int index = listaProduto.SelectedIndex;
double count = double.Parse(listaUnidade.Items[index].ToString());
soma -= count * precoBebidas[index];
listaUnidade.Items.RemoveAt(index);
listaPreco.Items.RemoveAt(index);
listaProduto.Items.RemoveAt(index);
txtPreco.Text = soma.ToString();
}
}
private void btnReduzQnt_Click(object sender, EventArgs e)
{
int index = -1;
if (listaProduto.SelectedIndex >= 0)
{
index = listaProduto.SelectedIndex;
}
else if (listaPreco.SelectedIndex >= 0)
{
index = listaPreco.SelectedIndex;
}
else if (listaUnidade.SelectedIndex >= 0)
{
index = listaUnidade.SelectedIndex;
}
if (index >= 0)
{
double count = double.Parse(listaUnidade.Items[index].ToString());
if (count > 1)
{
soma -= precoBebidas[index];
soma -= precoAlimentacao[index];
listaUnidade.Items[index] = count - 1;
listaPreco.Items[index] = Math.Round(precoBebidas[index] * (count - 1), 2);
listaPreco.Items[index] = Math.Round(precoAlimentacao[index] * (count - 1), 2);
txtPreco.Text = soma.ToString();
}
else
{
listaUnidade.Items.RemoveAt(index);
listaPreco.Items.RemoveAt(index);
listaProduto.Items.RemoveAt(index);
txtPreco.Text = soma.ToString();
}
}
}
private void btnFechoC_Click(object sender, EventArgs e)
{
txtPreco.Text = fecho.ToString();
txtPreco.BackColor = Color.Green;
txtPreco.ForeColor = Color.White;
txtPreco.Font = new Font("Microsoft Sans Serif", 11, FontStyle.Bold);
label2.Text = "Saldo Final";
MessageBox.Show("A caixa foi Encerrada.");
fecho = 0;
}
private void btnReturn_Click(object sender, EventArgs e)
{
}
}
}
I'm sorry about some of the Portuguese elements in the code. Can anyone help out on how to do this? I'm completly lost on this one.
I thought of creating an array and making every button click start by saving the "status quo" to the erray and having it update the listboxes through a button. But I couldn't implement it. The fixed numbers on arrays seems to be the factor.
When you say fixed numbers on arrays, do you mean that it is a hindrance that they can only be of pre-defined sizes?
If that's the case, then use a List. First import the necessary library then create the list, both as shown below:
using System.Collections.Generic;
List<type> myList = new List<type>();
You can add as many items to a list without pre-defining its size.
To append items to the list use:
myList.Append(someData);
To then access the last action made by the user (which you have already appended to the list), use:
type lastAction = myList[-1];
Related
I have looking for the solution but still found nothing
Here is my code:
private void Form1_Load(object sender, EventArgs e)
{
RichTextBox rtb = new RichTextBox();
rtb.Text = File.ReadAllText(#"C:\Users\Admin\Desktop\myfile\customers.txt");
int i = 0;
foreach (string line in rtb.Lines)
{
if (line == "--")
{
ListViewItem item = new ListViewItem();
item.Text = rtb.Lines[i + 1];
item.SubItems.Add(rtb.Lines[i + 2]);
item.SubItems.Add(rtb.Lines[i + 3]);
item.SubItems.Add(rtb.Lines[i + 4]);
listView1.Items.Add(item);
}
i += 1;
}
}
private void button1_Click(object sender, EventArgs e)
{
Form2 pop = new Form2();
pop.ShowDialog();
string name = pop.name;
int age = int.Parse(pop.Age);
string dob = pop.DateOfBirth;
string addr = pop.Address;
StreamWriter write = new StreamWriter(#"C:\Users\Admin\Desktop\myfile\customers.txt",true);
write.Write("--\n");
write.Write("{0}\n",name);
write.Write("{0}\n",dob);
write.Write("{0}\n",age);
write.Write("{0}\n",addr);
write.Close();
}
The question is how do I reload the list view after I write the data into the text file?
Extract the logic out of Form1_Load
private void Form1_Load(object sender, EventArgs e)
{
RefreshListView();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 pop = new Form2();
pop.ShowDialog();
string name = pop.name;
int age = int.Parse(pop.Age);
string dob = pop.DateOfBirth;
string addr = pop.Address;
StreamWriter write = new StreamWriter(#"C:\Users\Admin\Desktop\myfile\customers.txt",true);
write.Write("--\n");
write.Write("{0}\n",name);
write.Write("{0}\n",dob);
write.Write("{0}\n",age);
write.Write("{0}\n",addr);
write.Close();
RefreshListView();
}
private void RefreshListView()
{
listView1.Items.Clear();
RichTextBox rtb = new RichTextBox();
rtb.Text = File.ReadAllText(#"C:\Users\Admin\Desktop\myfile\customers.txt");
int i = 0;
foreach (string line in rtb.Lines)
{
if (line == "--")
{
ListViewItem item = new ListViewItem();
item.Text = rtb.Lines[i + 1];
item.SubItems.Add(rtb.Lines[i + 2]);
item.SubItems.Add(rtb.Lines[i + 3]);
item.SubItems.Add(rtb.Lines[i + 4]);
listView1.Items.Add(item);
}
i += 1;
}
}
I am trying to calculate the "change" due at the end of my program into a MessageBox. The Dollar amount entered into a text box needs to have the total subtracted from it but I just can't seem to see what I am doing wrong. Can anyone help me finish this?
namespace HardwareStore
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
ProductBox.Items.Add(new Hardware() { ItemNo = 1010, ProdName = "Hammer ", Price = (decimal)14.99d });
ProductBox.Items.Add(new Hardware() { ItemNo = 1056, ProdName = "Bag of Nails ", Price = (decimal)19.99d });
ProductBox.Items.Add(new Hardware() { ItemNo = 2001, ProdName = "Saw ", Price = (decimal)29.99d });
ProductBox.Items.Add(new Hardware() { ItemNo = 2005, ProdName = "Chainsaw ", Price = (decimal)69.99d });
ProductBox.Items.Add(new Hardware() { ItemNo = 3090, ProdName = "Ladder ", Price = (decimal)109.99d });
}
private void frmMain_Load(object sender, EventArgs e)
{
}
private void btnAddItem_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < int.Parse(txtQuantity.Text); i++)
ReceiptBox.Items.Add(ProductBox.Items[ProductBox.SelectedIndex]);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReceiptBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal subTotal = ReceiptBox.Items.Cast<Hardware>().Sum(item => item.Price);
decimal tax = Math.Round((subTotal * .075M), 2);
decimal total = subTotal + tax;
lblSub.Text = "$" + subTotal.ToString();
lblTax.Text = "$" + tax.ToString();
lblTotal.Text = "$" + total.ToString();
lblSub.Visible = true;
lblTax.Visible = true;
lblTotal.Visible = true;
}
private void btnChange_Click(object sender, EventArgs e)
{
MessageBox.Show("Change Due: $ ");
}
}
}
I think I caught it twice...
decimal total = 0; //declare the total as global variable
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal subTotal = ReceiptBox.Items.Cast<Hardware>().Sum(item => item.Price);
decimal tax = Math.Round((subTotal * .075M), 2);
total = subTotal + tax;
lblSub.Text = "$" + subTotal.ToString();
lblTax.Text = "$" + tax.ToString();
lblTotal.Text = "$" + total.ToString();
lblSub.Visible = true;
lblTax.Visible = true;
lblTotal.Visible = true;
}
private void btnChange_Click(object sender, EventArgs e)
{
decimal customerPay = 100;
if (total != 0){
decimal changeDue = customerPay - total;
txtDollar.Txt = "$ " + changeDue.toString();
MessageBox.Show("Change Due: " + txtDollar.Txt);
}
}
The Code is given below. it receives filepaths in a list from Form1 and then whole transformation takes place here and everything is working fine BUT the PROBLEM is that progressbar1 does not progress.. what could be the reason? Thanks in advance!
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
numericUpDown1.Enabled = false;
numericUpDown2.Enabled = false;
button1.Enabled = false;
}
List<string> filepath_ = new List<string>();
int count = 0, total = 0;
private string format = string.Empty;
private int _height = 0;
private int _width = 0;
internal void passpath(List<string> fp)
{
filepath_.AddRange(fp);
total = filepath_.Count;
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Stop")
{
backgroundWorker1.CancelAsync();
button1.Text = "Transform";
return;
}
else
{
button1.Text = "Stop";
System.Threading.Thread.Sleep(1);
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
foreach (string filepath in filepath_)
{
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
ImageFormat imageFormat = ImageFormat.Jpeg;
switch (format)
{
case "JPEG":
imageFormat = ImageFormat.Jpeg;
break;
break;
default:
break;
}
string finalpath = filepath.Substring(0, filepath.IndexOf('.'));
Image image1 = Image.FromFile(filepath);
string ext = Path.GetExtension(filepath);
if (_height != 0 && _width != 0 && format!=string.Empty)
{
Bitmap bitmap = new Bitmap(image1, _width, _height);
bitmap.Save(finalpath + " (" + _width.ToString() + "x" + _height.ToString() + ")." +format, imageFormat);
}
else if (_height != 0 && _width != 0)
{
Bitmap bitmap = new Bitmap(image1, _width, _height);
bitmap.Save(finalpath + " (" + _width.ToString() + "x" + _height.ToString() + ")" + ext);
}
else if (format != string.Empty)
{
Bitmap bitmap = new Bitmap(image1);
bitmap.Save(finalpath+"." + format, imageFormat);
}
count++;
int i = ((count / total) * 100);
backgroundWorker1.ReportProgress(i);
System.Threading.Thread.Sleep(1);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label6.Text = count.ToString() + " Out of " + total.ToString() + " Images transformed";
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
button1.Text = "Transform";
progressBar1.Value = 0;
if (e.Cancelled)
MessageBox.Show("Transformation stopped. " + count.ToString() + " images transformed.");
else if (e.Error != null)
MessageBox.Show(e.Error.Message);
else
{
MessageBox.Show(count.ToString() + " Images Transformed");
Application.Exit();
}
}
private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
format = ((ListBox)sender).SelectedItem.ToString();
button1.Enabled = true;
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
_width = 640;
_height = 480;
button1.Enabled = true;
}
}
}
}
Change you variables to doubles:
double count = 0, total = 0;
When you do this calculation:
int i = ((count / total) * 100);
You're currently doing integer arithmetic. The result of count / total (i.e 1 / 10 or 4 / 10) is rounded to 0. When you divide that by 100, the result is still 0, so your ProgressBar won't move.
Using the double type will correctly store the fractional part of your quotient.
The problem had already been pointed out by Grant Winney: It's the integer division.
Without changing data types of count and/or total you could use this:
int i = (int)((100.0 * count) / total)
or that:
int i = (100 * count) / total
where the former makes 100.0 * count a double and the division by total as well. The latter sticks to integer operations by simply multiplying count first (changing sequence of operations), such that the division will not be 0 as long as count is not 0.
pBar.Step = 2;
pBar.PerformStep();
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
The program is for a pizza menu, the button I click to add the pizza adds £3.00 on top of the actual total, I have looked for errors but can not find the problem. The program is not fully finished, only the adding of the pizza total is complete but something is wrong with the code which I can not find.
I also would like any suggestion to make the program more efficient.
string stuffedcrust;
string Deeppan;
string thincrispy;
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{ //Add type of crust to summary box
stuffedcrust = rbStuffedcrust.Text;
SummaryBox.Text = stuffedcrust;
}
private void button5_Click(object sender, EventArgs e)
{
Application.Exit();
}
private int clickCounter = 0;
private void button4_Click(object sender, EventArgs e) // Button to add the value pf the pizza to the text box
{
this.clickCounter++;
if (this.clickCounter < 10) // number of time the button can be pressed to add Pizzas
{
radioButton1.Checked = false;
radioButton2.Checked = false;
radioButton3.Checked = false;
radioButton4.Checked = false;
radioButton6.Checked = false;
radioButton7.Checked = false;
rbThinandcrispy.Checked = false;
rbStuffedcrust.Checked = false;
rbDeeppan.Checked = false;
checkBoxCrispyOnions.Checked = false;
checkBoxExtraCheese.Checked = false;
checkBoxPeppers.Checked = false;
checkBoxPepperoni.Checked = false;
checkBoxGarlicSauce.Checked = false;
checkBox12.Checked = false;
/*StreamWriter sw = new StreamWriter(SummaryBox.Text, true);
sw.WriteLine();
sw.WriteLine();
sw.WriteLine();
sw.WriteLine();
sw.Close(); */
MessageBox.Show("Pizza Added");
}
else
{
MessageBox.Show("No more Pizza's can be added, the maximum order is 10");
}
}
private void button7_Click(object sender, EventArgs e)
{
File.Create(textBox1.Text).Close();
}
private void button6_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
of.ShowDialog();
textBox1.Text = of.FileName;
}
public double PizzaPrice { get; set; } //Global Public
double ExtraTopping; //Global
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
string CT;
if (radioButton2.Enabled == true) //PIZZA CHEESE TOMATO
{
double ctp = 3.50;
PizzaPrice += ctp;
txtPizzaPrice.Text = "£ " + PizzaPrice.ToString();
CT = radioButton2.Text;
SummaryBox.Text = CT;
}
else
{
SummaryBox.Clear();
}
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
string VS;
if (radioButton1.Enabled == true) //PIZZA Veg SUpreme
{
double vsp = 5.20;
PizzaPrice += vsp;
txtPizzaPrice.Text = "£ " + PizzaPrice.ToString();
VS = radioButton1.Text;
SummaryBox.Text = VS;
}
else
{
SummaryBox.Clear();
}
}
private void radioButton3_CheckedChanged_1(object sender, EventArgs e)
{
string SV;
if (radioButton3.Enabled == true) //PIZZA SPicy Veg
{
double svp = 5.20;
PizzaPrice += svp;
txtPizzaPrice.Text = "£ " + PizzaPrice.ToString();
SV = radioButton3.Text;
SummaryBox.Text = SV;
}
else
{
SummaryBox.Clear();
}
}
private void radioButton6_CheckedChanged(object sender, EventArgs e)
{
string MF;
if (radioButton6.Enabled == true) //PIZZA MEAT FEAST
{
double mfp = 5.80;
PizzaPrice += mfp;
txtPizzaPrice.Text = "£ " + PizzaPrice.ToString();
MF = radioButton6.Text;
SummaryBox.Text = MF;
}
else
{
SummaryBox.Clear();
}
}
private void radioButton7_CheckedChanged(object sender, EventArgs e)
{
string HP;
if (radioButton7.Enabled == true) //PIZZA Ham pineapple
{
double hpp = 4.20;
PizzaPrice += hpp;
txtPizzaPrice.Text = "£ " + PizzaPrice.ToString();
HP = radioButton7.Text;
SummaryBox.Text = HP;
}
else
{
SummaryBox.Clear();
}
}
private void radioButton4_CheckedChanged(object sender, EventArgs e)
{
string SF;
if (radioButton4.Enabled == true) // PIZZA SEAFOOD
{
double sfp = 5.60;
PizzaPrice += sfp;
txtPizzaPrice.Text = "£ " + PizzaPrice.ToString();
SF = radioButton4.Text;
SummaryBox.Text = SF;
}
else
{
SummaryBox.Clear();
}
}
private void button1_Click(object sender, EventArgs e)
{
Bill sf = new Bill();
sf.Show(); // Open Bill
}
private void checkBox15_CheckedChanged(object sender, EventArgs e)
{ //EXTRA CHEESE
string EC;
if (checkBoxExtraCheese.Checked)
{
double ecp = .50;
ExtraTopping += ecp;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
EC = checkBoxExtraCheese.Text;
}
else
{
ExtraTopping = 0 + PizzaPrice;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
}
}
private void checkBox10_CheckedChanged(object sender, EventArgs e)
{ //PEPPERS
string PEP;
if (checkBoxPeppers.Checked)
{
double pepp = .50;
ExtraTopping += pepp;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
PEP = checkBoxPeppers.Text;
}
else
{
ExtraTopping = 0 + PizzaPrice;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
}
}
private void checkBoxCrispyOnions_CheckedChanged(object sender, EventArgs e)
{ //CRISPY ONIONS
string CO;
if (checkBoxCrispyOnions.Checked)
{
double cop = .50;
ExtraTopping += cop;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
CO = checkBoxCrispyOnions.Text;
}
else
{
ExtraTopping = 0 + PizzaPrice;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
}
}
private void checkBoxGarlicSauce_CheckedChanged(object sender, EventArgs e)
{ //Garlic Sauce
string GS;
if (checkBoxGarlicSauce.Checked)
{
double gsp = .50;
ExtraTopping += gsp;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
GS = checkBoxGarlicSauce.Text;
}
else
{
ExtraTopping = 0.0 + PizzaPrice;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
}
}
private void checkBoxPepperoni_CheckedChanged(object sender, EventArgs e)
{ //PEPPERONI
string Proni;
if (checkBoxPepperoni.Checked)
{
double pepperoni = .50;
ExtraTopping += pepperoni;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
Proni = checkBoxPepperoni.Text;
}
else
{
ExtraTopping = 0 + PizzaPrice;
txtPizzaPrice.Text = "£ " + ExtraTopping.ToString();
}
}
private void rbThinandcrispy_CheckedChanged(object sender, EventArgs e)
{ //Add type of crust to summary box
thincrispy = rbThinandcrispy.Text;
SummaryBox.Text = thincrispy;
}
private void rbDeeppan_CheckedChanged(object sender, EventArgs e)
{ //Add type of crust to summary box
Deeppan = rbDeeppan.Text;
SummaryBox.Text = Deeppan;
}
Menu(object sender, System.ComponentModel.CancelEventArgs e)
{
clickCounter--;
}
}
}
Your code is fairly confusing, particularly because of controls with names like radioButton1, radioButton2, etc...
It looks like your issue could be stemming from the fact that when your pizza type radio buttons change state, you add the price of the newly selected pizza to the pizza price instead of replacing it.
I would strongly encourage you to adopt an object-oriented approach in your application. If you create a Pizza class with fields for extra toppings, each Pizza that you add to an order will know everything that should be on it and how much it costs in total, and the Pizza could have a .ToString() overload that would build the summary text you're looking for: i.e., "Supreme pizza (4.50) : cheese (.50), crispy onions (.50) = Total: 5.50"
Separating your business objects from the UI elements (checkboxes, radio buttons, text fields) will vastly simplify what you're trying to do.
This is a guess but your add button only sets all your check boxes.Checked = false and then displays a popup. It never actually adds the price of the current pizza selected to any totals.
i'm wrtting a code in visual studio c# that converts integers from binary to decimal mode and from decimal mode to binary but i want it to converts numbers with decimal points from decimal mode to binary how can i do this please help me and tell me what modifies i must put in my code
this is my code for the calculator :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace assignment2
{
public partial class Form1 : Form
{
const int asciiDiff = 48;
double num1 = 0, num2 = 0, result = 0;
double fact = 1;
int[] iHexaNumeric = new int[] { 10, 11, 12, 13, 14, 15 };
char[] cHexa = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' };
String a = "";
char op;
bool b = false;
const int base10 = 10;
public Form1()
{
//
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "1";
}
private void buttonTow_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "2";
}
private void buttonThree_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "3";
}
private void buttonFour_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "4";
}
private void buttonFive_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "5";
}
private void buttonSix_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "6";
}
private void buttonSeven_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "7";
}
private void buttonEight_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "8";
}
private void buttonNine_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "9";
}
private void buttonZero_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "0";
}
private void buttonPlus_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(DisplayResult.Text.ToString());
op = '+';
DisplayResult.Text = string.Empty;
}
private void buttonMinus_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(DisplayResult.Text.ToString());
op = '-';
DisplayResult.Text = string.Empty;
}
private void buttonMultipler_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(DisplayResult.Text.ToString());
op = '*';
DisplayResult.Text = string.Empty;
}
private void buttonDivider_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(DisplayResult.Text.ToString());
op = '/';
DisplayResult.Text = string.Empty;
}
private void buttonEqual_Click(object sender, EventArgs e)
{
if (DisplayResult.Text == "")
return;
else
{
try
{
num2 = Convert.ToDouble(DisplayResult.Text.ToString());
switch (op)
{
case '+': //suma
result = (num1 + num2);
DisplayResult.Text = result.ToString();
break;
case '-': //resta
result = (num1 - num2);
DisplayResult.Text = result.ToString();
break;
case '*': //multiply
result = (num1 * num2);
DisplayResult.Text = result.ToString();
break;
case '/': //division
if (num2 != 0)
{
result = (num1 / num2);
DisplayResult.Text = result.ToString();
}
else
{
DisplayResult.Text = "Can't divide by 0";
}
break;
}
}
catch (Exception ex)
{
MessageBox.Show("Unexpected error occured. Details: " +
ex.Message);
}
}
}
private void buttonBackSpace_Click(object sender, EventArgs e)
{
try
{
String Value = DisplayResult.Text.ToString();
int temp = Value.Length;
if (temp == 1)
DisplayResult.Text = String.Empty;
else
{
DisplayResult.Text = DisplayResult.Text.Substring(0, temp - 1);
}
}
catch (Exception ex)
{
MessageBox.Show("Unexpected error in buttonBackSpace occured. Details: " +
ex.Message);
}
}
private void buttonClear_Click(object sender, EventArgs e)
{
DisplayResult.Text = String.Empty;
}
private void buttonDecimal_Click(object sender, EventArgs e)
{
if (DisplayResult.Text.Contains("."))
{
return;
}
DisplayResult.Text += ".";
}
private void DecimalRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (DecimalRadioButton.Checked == true)
{
DisplayResult.Text= BaseToDecimal(DisplayResult.Text.ToString(), 2).ToString();
}
buttonTow.Enabled = true;
buttonThree.Enabled = true;
buttonFour.Enabled = true;
buttonFive.Enabled = true;
buttonSix.Enabled = true;
buttonSeven.Enabled = true;
buttonEight.Enabled = true;
buttonNine.Enabled = true;
}
private void BinaryRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (BinaryRadioButton.Checked == true)
{
DisplayResult.Text = DecimalToBase(Convert.ToInt16(DisplayResult.Text.ToString()), 2);
buttonTow.Enabled = false;
buttonThree.Enabled = false;
buttonFour.Enabled = false;
buttonFive.Enabled = false;
buttonSix.Enabled = false;
buttonSeven.Enabled = false;
buttonEight.Enabled = false;
buttonNine.Enabled = false;
}
}
string DecimalToBase(int iDec, int numbase)
{
string strBin = "";
int[] result = new int[32];
int MaxBit = 32;
for (; iDec > 0; iDec /= numbase)
{
int rem = iDec % numbase;
result[--MaxBit] = rem;
}
for (int i = 0; i < result.Length; i++)
if ((int)result.GetValue(i) >= base10)
strBin += cHexa[(int)result.GetValue(i) % base10];
else
strBin += result.GetValue(i);
strBin = strBin.TrimStart(new char[] { '0' });
return strBin;
}
int BaseToDecimal(string sBase, int numbase)
{
int dec = 0;
int b;
int iProduct = 1;
string sHexa = "";
if (numbase > base10)
for (int i = 0; i < cHexa.Length; i++)
sHexa += cHexa.GetValue(i).ToString();
for (int i = sBase.Length - 1; i >= 0; i--, iProduct *= numbase)
{
string sValue = sBase[i].ToString();
if (sValue.IndexOfAny(cHexa) >= 0)
b = iHexaNumeric[sHexa.IndexOf(sBase[i])];
else
b = (int)sBase[i] - asciiDiff;
dec += (b * iProduct);
}
return dec;
}
}
}
When converting a number with a decimal point from decimal to binary, this is what you do: first you take the part before the decimal point and convert it (in the usual way) to binary; and the part after the decimal point you multiply by 2 and see if it is >= 1; if it is not, write 0 and keep multiplying. You are done when it is = 1.00. For example:
2.25 -
You take the 0.25;
0.25 * 2 = 0.50 --> 0,
0.50 * 2 = 1.00 --> 1, and you just read the numbers.
So, 0.25 would be 0.01 (2.25 would be 10.01 binary.)