I have a form that has two buttons, textbox, listbox, and a combobox. The problem I am having is when I am trying to total button. I can not figure out how to get the cost values from this list, so I can total the total cost of the order. Thanks for the suggestions.
private void Order_Click(object sender, EventArgs e)
{
amount = int.Parse(textBox1.Text);
cost *= amount;
if (comboBox1.SelectedItem.ToString() == "Eggs")
{
listBox1.Items.Add("The cost for " + amount + "
dozen large, fresh eggs is: " + (cost).ToString("C"));
comboBox1.Text = "";
textBox1.Text = "0";
textBox1.Focus();
comboBox1.Focus();
}
else if (comboBox1.SelectedItem.ToString() == "Milk")
{
if (amount == 1)
{
listBox1.Items.Add
("The Cost for a fresh quart milk is: " + (cost).ToString("C"));
comboBox1.Text = "";
comboBox1.Focus();
textBox1.Text = "0";
textBox1.Focus();
}
else
{
listBox1.Items.Add
("The Cost for " + amount + " quarts of fresh milk is: " +
(cost).ToString("C"));
comboBox1.Text = "";
comboBox1.Focus();
textBox1.Text = "0";
textBox1.Focus();
}
}
else
{
listBox1.Items.Add
("The Cost for " + amount + " fresh loafs of bread is: " + (cost).ToString("C"));
comboBox1.Text = "";
comboBox1.Focus();
textBox1.Text = "0";
textBox1.Focus();
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "Eggs")
{
cost = 1.90;
label1.Text = "The Cost is " + (cost).ToString("C") + " per dozen";
}
else if (comboBox1.SelectedItem.ToString() == "Milk")
{
cost = 1.47;
label1.Text = "The Cost is " + (cost).ToString("C") + " per quart";
}
else
{
cost = 2.12;
label1.Text = "The Cost is " + (cost).ToString("C") + " per loaf";
}
}
private void total_Click(object sender, EventArgs e)
{
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
if (e.KeyChar == '.'
&& (sender as TextBox).Text.IndexOf('.') > -2)
{
e.Handled = true;
}
if (e.KeyChar == '-'
&& (sender as TextBox).Text.IndexOf('-') > -2)
{
e.Handled = true;
}
}
}
}
Why not use a total class field and add the amount to it each time you add an item to the list box? Then you would always have the total cost without having to try to parse it back out of the list.
public partial class Form1 : Form
{
private double cost;
private double total;
int amount = 0;
public Form1()
{
InitializeComponent();
}
private void Order_Click(object sender, EventArgs e)
{
amount = int.Parse(textBox1.Text);
cost *= amount;
total += cost;
...
}
Related
UPDATE: I added my code to show the whole process and this is somehow a continuation to my last question
I have 3 items listed in my listview and a if statement which states that if my subitem is Inactive code inside will generate a file. My problem is once the Inactive item/s is Active again, how will I make my timer to move again?
private void Form1_Load(object sender, EventArgs e)
{
timer2.Enabled = true;
}
private void running_process()
{
Process[] processes = Process.GetProcesses("ITWORKSPC152");
for (int i = 0; i < listView1.Items.Count; i++)
{
if (flag == false)
{
listView1.Items[i].SubItems.Add("Inactive");
if(i == listView1.Items.Count - 1)
flag = true;
}
foreach (Process p in processes)
{
if (!listBox1.Items.Contains(listView1.Items[i].Text))
{
listView1.Items[i].SubItems[1].Text = " ";
listView1.Items[i].SubItems[1].Text = "Inactive";
listView1.Items[i].BackColor = Color.Red;
}
if (listView1.Items[i].Text == p.ProcessName)
{
listBox1.Items.Add(p.ProcessName);
listView1.Items[i].SubItems[1].Text = "Inactive";
for (int j = 0; j < listBox1.Items.Count; j++)
{
if (listBox1.Items[j].ToString() == listView1.Items[i].Text)
{
listView1.Items[i].SubItems[1].Text = "Active";
listView1.Items[i].BackColor = Color.FromArgb(66, 181, 33);
//m_boolIsDown = false;
}
}
}
}
}
}
private void InactiveCheck()
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].SubItems[1].Text == "Inactive")
{
richTextBox1.Text = richTextBox1.Text + listView1.Items[i].Text +
" was inactive at " + DateTime.Now.ToString("hh':'mm tt") + "\n";
File.AppendAllText(#"C:\Documents and Settings\pamojica\My Documents\InactiveProgramLogs\" + lbl_date.Text + ".txt", richTextBox1.Text);
timer3.Enabled = false;
}
else
{
timer3.Enabled = true;
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
listBox1.Items.Clear();
richTextBox1.Clear();
running_process();
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void timer3_Tick(object sender, EventArgs e)
{
InactiveCheck();
}
private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i] == null || listView1.Items.Count == 0)
return;
var item = listView1.Items[i];
if (item.SubItems != null && item.SubItems.Count > 1 && item.SubItems[1].Text == "Inactive")
{
richTextBox1.Text = richTextBox1.Text + item.Text + " was inactive at " + DateTime.Now.ToString("hh':'mm tt") + "\n";
File.AppendAllText(#"C:\Documents and Settings\pamojica\My Documents\InactiveProgramLogs\" + lbl_date.Text + ".txt", richTextBox1.Text);
}
}
}
You do not need Timer at all. In your case, the problem is: you want to do something when the value of your item in the listview changes. "event" is the key word here.
Subscribe to an event of your ListView, choose one here. I think that in that list the event "AfterLabelEdit" is the one you are looking for.
Here is some clues, maybe you should adapt the code to your specific context:
listView1.AfterLabelEdit += (o, e) =>
{
if (listView1.SelectedItems == null || listView1.SelectedItems.Count == 0)
return;
var item = listView1.SelectedItems[0];
if (item.SubItems != null && item.SubItems.Count > 1 && item.SubItems[1].Text == "Inactive")
{
richTextBox1.Text = richTextBox1.Text + item.Text + " was inactive at " + DateTime.Now.ToString("hh':'mm tt") + "\n";
File.AppendAllText(#"C:\Documents and Settings\pamojica\My Documents\InactiveProgramLogs\" + lbl_date.Text + ".txt", richTextBox1.Text);
}
};
Generally speaking, there is almost no simple UI hanlding case where a timer is needed. Just use event.
In a "ListView point of view", using a timer is like:
"I will look around if something changed. If not, I will recheck in a few milliseconds. I will be very busy."
The (better) logic with event is:
"Hey you, controls. All of you: when something changes... keep me posted!"
Instead of doing timer3.Enabled = true; or timer3.Enabled =false
use timer3.Start(); and timer3.Stop()
Stop the Timer in Tick Event will do the trick
private void Form1_Load(object sender, EventArgs e)
{
timer3.Start();
}
private void InactiveCheck()
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].SubItems[1].Text == "Inactive")
{
richTextBox1.Text = richTextBox1.Text + listView1.Items[i].Text + " was inactive at " + DateTime.Now.ToString("hh':'mm tt") + "\n";
File.AppendAllText(#"C:\Documents and Settings\pamojica\My Documents\InactiveProgramLogs\" + lbl_date.Text + ".txt", richTextBox1.Text);
}
else
{
timer3.Start();
}
}
}
private void timer3_Tick(object sender, EventArgs e)
{
timer3.Stop()
InactiveCheck();
}
Use timer3.Stop(); or timer3.Start(); methods in a ItemSelectionChanged event
private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (e.Item == sender)
{
if (e.IsSelected) timer3.Start();
else timer3.Stop();
}
}
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 am designing a basic calculator using C#. I am facing difficulties while I am entering a decimal point. Example, if I am entering .8 then it gives me 0.8 which is correct if there is nothing on the display screen but after that if I am entering the decimal symbol, then also it accepts it that is 0.8..... I want only one decimal symbol to be accepted for one number. My code is
private void btn_Decimal_Click(object sender, EventArgs e)
{
if (txt_Result.Text == "" || LastcharIssymbol==true)
{
txt_Result.Text = txt_Result.Text + 0 + ".";
}
else
txt_Result.Text = txt_Result.Text + ".";
}
Here, if I am entering 0.9.999 then also it accepts and if I am entering 999..... then also it accepts. I want only one decimal symbol to be accepted for one number that is 999.999. Please help me. Also I am adding two additional labels that can show the current system date and time. I am unable to show the date as well as the time but I am able to show the date and time using VB.Net. I don't know where I am getting the errors. My whole code is
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 CS_Calculator
{
public partial class Form1 : Form
{
Boolean LastcharIssymbol {get;set;}
string op;
double a, memory;
public Form1()
{
InitializeComponent();
}
private void btn_1_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "1";
LastcharIssymbol= false;
}
private void btn_2_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "2";
LastcharIssymbol = false;
}
private void btn_3_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "3";
LastcharIssymbol = false;
}
private void btn_4_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "4";
LastcharIssymbol = false;
}
private void btn_5_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "5";
LastcharIssymbol = false;
}
private void btn_6_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "6";
LastcharIssymbol = false;
}
private void btn_7_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "7";
LastcharIssymbol = false;
}
private void btn_8_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "8";
LastcharIssymbol = false;
}
private void btn_9_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "9";
LastcharIssymbol = false;
}
private void btn_0_Click(object sender, EventArgs e)
{
txt_Result.Text = txt_Result.Text + "0";
LastcharIssymbol = false;
}
private void btn_Decimal_Click(object sender, EventArgs e)
{
if (txt_Result.Text == "" || LastcharIssymbol==true)
{
txt_Result.Text = txt_Result.Text + 0 + ".";
}
else
txt_Result.Text = txt_Result.Text + ".";
}
private void btn_Plus_Click(object sender, EventArgs e)
{
if(txt_Result.Text=="" || LastcharIssymbol)
{
MessageBox.Show("Please Enter first number to perform the addition operation.");
}
else
{
op = "+";
txt_Result.Text = txt_Result.Text + op;
LastcharIssymbol=true;
}
}
private void btn_Minus_Click(object sender, EventArgs e)
{
if (txt_Result.Text == "" || LastcharIssymbol)
{
MessageBox.Show("Please enter first number to erform the substraction operation.");
}
else
{
op = "-";
txt_Result.Text = txt_Result.Text + op;
LastcharIssymbol = true;
}
}
private void btn_Division_Click(object sender, EventArgs e)
{
if (txt_Result.Text == "" || LastcharIssymbol)
{
MessageBox.Show("Please enter first number to perform the division operation.");
}
else
{
op = "/";
txt_Result.Text = txt_Result.Text + op;
LastcharIssymbol = true;
}
}
private void btn_Mult_Click(object sender, EventArgs e)
{
if (txt_Result.Text == "" || LastcharIssymbol)
{
MessageBox.Show("Please enter first number to perform the multiplication operation.");
}
else
{
op = "*";
txt_Result.Text = txt_Result.Text + op;
LastcharIssymbol = true;
}
}
private void btn_Equal_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
txt_Result.Text = "";
}
private void btn_Clear_All_Click(object sender, EventArgs e)
{
txt_Result.Text = "";
op = "";
a = 0;
memory = 0;
}
private void btn_Memory_Click(object sender, EventArgs e)
{
memory = Convert.ToDouble(txt_Result.Text);
}
private void btn_Show_Memory_Click(object sender, EventArgs e)
{
txt_Result.Text = memory.ToString();
}
}
}
You should disable the decimal once it is clicked and enable it again if any of the operator or 'C' is pressed.
if (!txt_Result.Text.Contains("."))
if(txt_Result.Text == string.Empty)
txt_Result.Text = "0.";
else
txt_Result.Text += ".";
else
MessageBox.Show("more dots are not allowd");
for the case you have text like '11.9+12' which has operations in it you can do the following
string formula = "11.9/1.2*99.9+19";
string lastPiece = formula.Split(new char[] { '+', '-', '*', '/' })[formula.Split(new char[] { '+', '-', '*', '/' }).Count() - 1];
if (!lastPiece.Contains('.')) formula += ".";
//adds dot
lastPiece = formula.Split(new char[] { '+', '-', '*', '/' })[formula.Split(new char[] { '+', '-', '*', '/' }).Count() - 1];
if (!lastPiece.Contains('.')) formula += ".";
//does not add dot
MessageBox.Show(formula);
//output : 11.9/1.2*99.9+19.
You could use decimal.TryParse to test whether the string is a valid decimal number. If not, such as if your input has two decimal points, then the TryParse call fails.
TryParse is a good option because there can be many issues with an entered number besides a doubled decimal point such as... a triple decimal point, a misplaced minus sign, alpha chars etc.
Try:
private void btn_Decimal_Click(object sender, EventArgs e)
{
decimal num;
if (!Decimal.TryParse(txt_Result.Text, out num))
{
MessageBox.Show(txt_Result.Text + " is not a valid number.");
return;
}
if (txt_Result.Text == "" || LastcharIssymbol==true)
txt_Result.Text = txt_Result.Text + 0 + ".";
else
txt_Result.Text = txt_Result.Text + ".";
}
private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)//textprice key pressed
{
if ((e.KeyChar < '0' || e.KeyChar > '9') && (e.KeyChar != '\b') && (e.KeyChar != '.'))
{
e.Handled = true;
}
else
{
e.Handled = false;
}
if (Char.IsControl(e.KeyChar))
{
e.Handled = false;
}
else if (Char.IsNumber(e.KeyChar) || e.KeyChar == '.')
{
TextBox tb = sender as TextBox;
int cursorPosLeft = tb.SelectionStart;
int cursorPosRight = tb.SelectionStart + tb.SelectionLength;
string result = tb.Text.Substring(0, cursorPosLeft) + e.KeyChar + tb.Text.Substring(cursorPosRight);
string[] parts = result.Split('.');
if (parts.Length > 1)
{
if (parts[1].Length > 2 || parts.Length > 2)
{
e.Handled = true;
}
}
}
Change your last else to:
else if (!txt_Result.Text.Contains (".")) {
txt_Result.Text = txt_Result.Text + ".";
}
Or consider disabling the decimal point button.
You should probably do some validation on the value to ensure it is a valid number.
**Another example , 100% **
private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
{
if (txtPrice.Text.Length == 0)
{
if (e.KeyChar == '.')
{
e.Handled = true;
}
}
if (!char.IsDigit(e.KeyChar) && e.KeyChar != 8 && e.KeyChar != 46)
{
e.Handled = true;
}
if (e.KeyChar == '.' && txtPrice.Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
This works for me:
if (!txt_Result.Text.Contains("."))
if(txt_Result.Text == string.Empty)
txt_Result.Text = "0.";
else
MessageBox.Show("Sorry, invalid number format!
Value can't have more than a decimal point");
else
txt_Result.Text += ".";
Put this code in textbox_keypress
here txtweight is my textbox name you use yours
private void txtweight_KeyPress(object sender, KeyPressEventArgs e)
{
if (txtweight.Text.Length == 0)
{
if (e.KeyChar == '.')
{
e.Handled = true;
}
}
if (!char.IsDigit(e.KeyChar) && e.KeyChar != 8 && e.KeyChar != 46)
{
e.Handled = true;
}
if (e.KeyChar == '.' && txtweight.Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}