Using Timer to detect changes - c#

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

Related

Tasked to create an Undo button in C#

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];

How to stop timer if a Listbox is empty or items are less than 0 in winform applications

I am making a windows app.
A button1 which gets the items in listBox1 from server at the start.
A button2 which starts the timer1.
A timer1 which removes items from listBox1 .
A progressBar1 which shows the progress of this process.
Here is the code:
private void button1_Click(object sender, EventArgs e)
{
jabber.Send("<iq type='get' to='" + textBox1.Text + "#conference.jabber.com' id='qip_1026'><query xmlns='http://jabber.org/protocol/muc#admin'><item affiliation='outcast' /></query></iq>");
}
private void button2_Click(object sender, EventArgs e)
{
progressBar1.Maximum = listBox1.Items.Count;
timer1.Start();
timer1.Interval = 4000;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (listBox1.Items.Count > 0)
{
jabber.Send("<iq type='set' to='" + textBox7.Text + "#conference.jabber.com'><query xmlns='http://jabber.org/protocol/muc#admin'><item jid='" + listBox1.Items[0].ToString() + "' affiliation='none'/></query></iq>");
listBox1.Items.RemoveAt(0);
progressBar1.Value += 1;
label.Text = listBox1.Items.Count.ToString();
}
else
{
timer1.Enabled = False;
}
}
The above code works well till there is one item left in listBox1.
The error is:
System.ArgumentOutOfRangeException was unhandled
Message=InvalidArgument=Value of '0' is not valid for 'index'.
Parameter name: index
It raises an error when listBox1 reaches 0. I want to stop the timer when listbox1 is empty or gets no items or 0 items.
The problem is in this code:
private void timer1_Tick(object sender, EventArgs e)
{
if (listBox1.Items.Count > 0)
{
jabber.Send("<iq type='set' to='" + textBox7.Text + "#conference.jabber.com'><query xmlns='http://jabber.org/protocol/muc#admin'><item jid='" + listBox1.Items[0].ToString() + "' affiliation='none'/></query></iq>");
listBox1.Items.RemoveAt(0);
progressBar1.Value += 1;
label.Text = listBox1.Items.Count.ToString();
}
else
{
timer1.Enabled = False;
}
}
So what is happening is that you are using count to check >0 then calling jabber to do the work, It the call becomes slow- you will see multiple timers getting fired back. So a big queue will be collected there. You need to modify the code a bit here using lock to hold the list and allow jabber to do its work:
private void timer1_Tick(object sender, EventArgs e)
{
lock (listBox1)
{
if (listBox1.Items.Count > 0)
{
jabber.Send("<iq type='set' to='" + textBox7.Text +
"#conference.jabber.com'><query xmlns='http://jabber.org/protocol/muc#admin'><item jid='" +
listBox1.Items[0].ToString() + "' affiliation='none'/></query></iq>");
listBox1.Items.RemoveAt(0);
progressBar1.Value += 1;
label.Text = listBox1.Items.Count.ToString();
}
else
{
timer1.Enabled = False;
}
}
}
Lock will also ensure that the items are removed correctly.
To save the file as per comment below :
public class ChatHistoryManager
{
private readonly RichTextBox richTextBox;
private Timer timer = new Timer();
public ChatHistoryManager(RichTextBox richTextBox)
{
this.richTextBox = richTextBox;
this.InitializeTimer();
}
public string Location { get; set; }
private void InitializeTimer()
{
this.timer.Tick += timer_Tick;
this.timer.Enabled = true;
this.timer.Interval = (int) TimeSpan.FromHours(1).TotalMilliseconds;
}
void timer_Tick(object sender, EventArgs e)
{
this.SaveFile();
}
public void SaveFile()
{
//Save the file to the location
this.richTextBox.SaveFile(this.Location,RichTextBoxStreamType.RichText);
}
public void Stop()
{
this.timer.Stop();
}
}
Now we need to set in form like this:
private void Form1_Load(object sender, EventArgs e)
{
ChatHistoryManager chatHistoryManager = new ChatHistoryManager(this.richTextBox1);
chatHistoryManager.Location = #"C:\Development\test.txt";
}
try this
int count = City.Items.Count - 1;
for (int i = count; i > 0; i--){
City.Items.RemoveAt(i);
}
Here is what worked for me.
private void button1_Click(object sender, EventArgs e)
{
jabber.Send("<iq type="get" to="" + textBox1.Text + "#conference.jabber.com" id="qip_1026"><query xmlns="http://jabber.org/protocol/muc#admin"><item affiliation="outcast" /></query></iq>");
}
private void button2_Click(object sender, EventArgs e)
{
progressBar1.Maximum = listBox1.Items.Count;
progressBar1.Value = 0;
// Set the timer interval to four seconds
timer1.Interval = 4000;
// Start the timer
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
// Disable the timer while we are working in this procedure so
// it doesn't tick while we are working in this procedure
timer1.Enabled = False;
// Send only if there are items in the ListBox
if (listBox1.Items.Count > 0)
{
jabber.Send("<iq type="set" to="" + textBox7.Text + "#conference.jabber.com"><query xmlns="http://jabber.org/protocol/muc#admin"><item jid="" + listBox1.Items[0].ToString() + "" affiliation="none" /></query></iq>");
listBox1.Items.RemoveAt(0);
progressBar1.Value += 1;
label.Text = listBox1.Items.Count.ToString();
}
// Re-enable only if there are items left in the ListBox
if (listBox1.Items.Count > 0)
{
timer1.Enabled = True;
}
}

When I click the button it adds £3.00 to the total on top of what is correct [closed]

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.

C# windows form listbox totaling

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;
...
}

My application won't run under .net 2.0 , works on 3.5

I made this windows forms application in .net 3.5 (VS c# express) .
Now I want to convert it so it can run with just .net 2.0 installed. SO in my project properties: I selected "target framework " as 2.0 , fixed the errors that I got.
After this the app runs fine with .net 3.0 installed , but won't run on a fresh install of xp with with .net 2.0 installed. "Application has crashed. send error report"
What do I do ? I want this thing to run under 2.0.
here is the code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Xml;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int numberOfMatches = 0;
string[,] data;
bool update = true ;
string fileToParse = Path.GetTempPath() + "cricketfile.xml";
int matchToShow = 0;
bool showschedule = true ;
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd,
int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
public Form1()
{
InitializeComponent();
if (Environment.OSVersion.Version.Major <= 5)
{
// MessageBox.Show("xp");
}
else
{
label1.Top = 1;
pictureBox1.Top = 1;
}
// label1.Left = 1;
int X = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width / 2 - this.Width / 2;
this.Location = new System.Drawing.Point(X, -5);
if (rkApp.GetValue("cricketscore") == null)
{
startWithWindowsToolStripMenuItem.Checked = false ;
}
else
{
startWithWindowsToolStripMenuItem.Checked = true ;
}
this.Region = new Region(new Rectangle(10, 10, 197, 17));
ToolTip tooltip = new ToolTip();
// MessageBox.Show(" F" + tooltip.AutomaticDelay);
tooltip.AutomaticDelay = 0;
tooltip.InitialDelay = 0;
tooltip.SetToolTip(pictureBox1, " right click for settings, left click to move");
tooltip.SetToolTip(label1, " right click for settings, left click to move");
fetchData();
addContextEntries();
chooseIndia();
updateScore();
// MessageBox.Show(data.GetLength(0).ToString());
//foreach (string s in data)
//{
// Console.WriteLine(s);
//}
timer1.Interval = 20 * 1000;
timer1.Enabled = true;
}
public void addContextEntries()
{
// MessageBox.Show("num- " + numberOfMatches);
List<ToolStripMenuItem> Mylist1 = new List<ToolStripMenuItem>();
for (int i = 0; i < numberOfMatches; i++)
{
Mylist1.Add( new ToolStripMenuItem() );
this.contextMenuStrip1.Items.Add(Mylist1[i]);
Mylist1[i].Text = "See Match " + (i + 1) + "'s score";
switch(i)
{
case 0:
Mylist1[i].Click += new System.EventHandler(this.match1);
break;
case 1:
Mylist1[i].Click += new System.EventHandler(this.match2);
break;
case 2:
Mylist1[i].Click += new System.EventHandler(this.match3);
break;
case 3:
Mylist1[i].Click += new System.EventHandler(this.match4);
break;
case 4:
Mylist1[i].Click += new System.EventHandler(this.match5);
break;
}
}
}
public void match1(object sender, EventArgs e)
{
// MessageBox.Show("match 1");
matchToShow = 0;
label1.Text = data[0, 0] + " " + data[0, 1];
}
public void match2(object sender, EventArgs e)
{
// MessageBox.Show("match 2");
matchToShow = 1;
label1.Text = data[1, 0] + " " + data[1, 1];
}
public void match3(object sender, EventArgs e)
{
matchToShow = 2;
label1.Text = data[2, 0] + " " + data[2, 1];
}
public void match4(object sender, EventArgs e)
{
matchToShow = 3;
label1.Text = data[3, 0] + " " + data[3, 1];
}
public void match5(object sender, EventArgs e)
{
matchToShow = 4;
label1.Text = data[4, 0] + " " + data[4, 1];
}
public void chooseIndia()
{
try
{
for (int i = 0; i < data.GetLength(0); i++)
{
// MessageBox.Show("i - " + i);
if (data[i, 3].ToLower().Contains("india"))
{
matchToShow = i;
// MessageBox.Show("i - " + i);
break;
}
}
}
catch (NullReferenceException ne)
{
}
}
public void updateScore()
{
fetchData();
if (update == true)
{
try
{
label1.Text = data[matchToShow, 0] + " " + data[matchToShow, 1];
}
catch (Exception e)
{
}
}
}
public void fetchData()
{
int matchnumber = -1;
numberOfMatches = 0;
WebClient Client = new WebClient();
try
{
Client.DownloadFile("http://synd.cricbuzz.com/score-gadget/gadget-scores-feed.xml", fileToParse);
}
catch (WebException we)
{
// if (we.ToString().ToLower().Contains("connect to"))
// MessageBox.Show("sdf");
label1.Text = "No Internet";
update = false ;
this.Update();
// System.Threading.Thread.Sleep(1000);
}
try
{
XmlTextReader xmlreader0 = new XmlTextReader(fileToParse);
while (xmlreader0.Read())
{
if (xmlreader0.Name.ToString() == "match" && xmlreader0.NodeType == XmlNodeType.Element)
{
++numberOfMatches;
}
}
data = new string[numberOfMatches, 4];
// numberOfMatches = 0;
// MessageBox.Show("matchnumbers - " + numberOfMatches);
// MessageBox.Show("asd");
XmlTextReader xmlreader = new XmlTextReader(fileToParse);
while (xmlreader.Read())
{
// MessageBox.Show("READING");
if (xmlreader.Name.ToString() == "header" && xmlreader.NodeType == XmlNodeType.Element)
{
xmlreader.Read();
data[matchnumber, 0] = xmlreader.Value;
// MessageBox.Show(xmlreader.Value);
}
if (xmlreader.Name == "description" && xmlreader.NodeType == XmlNodeType.Element)
{
// MessageBox.Show(xmlreader.Value);
xmlreader.Read();
// MessageBox.Show("matched - " + xmlreader.Value);
data[matchnumber, 1] = xmlreader.Value;
}
if (xmlreader.Name == "url-text" && xmlreader.NodeType == XmlNodeType.Element)
{
xmlreader.Read();
// MessageBox.Show(xmlreader.Value);
data[matchnumber, 2] = xmlreader.Value;
}
if (xmlreader.Name == "url-link" && xmlreader.NodeType == XmlNodeType.Element)
{
xmlreader.Read();
data[matchnumber, 3] = xmlreader.Value;
}
if (xmlreader.Name.ToString() == "match" && xmlreader.NodeType == XmlNodeType.Element)
{
matchnumber++;
showFullScorecardToolStripMenuItem.Text = "Show full scorecard";
showschedule = true;
update = true;
}
if (xmlreader.Name.ToString() == "nextlive" && xmlreader.NodeType == XmlNodeType.Element)
{
label1.Text = "No current match";
showFullScorecardToolStripMenuItem.Text = "Show Schedule";
showschedule = false;
update = false;
break;
}
}
xmlreader.Close();
xmlreader0.Close();
}
catch (FileNotFoundException fe)
{
// MessageBox.Show("no internet");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
updateScore();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void switchColrosToolStripMenuItem_Click(object sender, EventArgs e)
{
if ( label1.ForeColor == System.Drawing.Color.Black)
label1.ForeColor = System.Drawing.Color.White ;
else
label1.ForeColor = System.Drawing.Color.Black;
}
private void startWithWindowsToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void startWithWindowsToolStripMenuItem_CheckStateChanged(object sender, EventArgs e)
{
if (startWithWindowsToolStripMenuItem.Checked == true)
{
rkApp.SetValue("cricketscore", Application.ExecutablePath.ToString());
}
else
{
rkApp.DeleteValue("cricketscore", false);
}
}
private void showFullScorecardToolStripMenuItem_Click(object sender, EventArgs e)
{
if ( showschedule == true )
System.Diagnostics.Process.Start(data[matchToShow, 3]);
else
System.Diagnostics.Process.Start("http://www.cricbuzz.com/component/cricket_schedule/");
}
private void label1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
//public void findNumberOfMatches()
//{
// if (xmlreader.Name.ToString() == "match" && xmlreader.NodeType == XmlNodeType.Element)
// {
// matchnumber++;
// }
//}
}
}
Thanks
The way it closes doesn't look like need to upgrade the framework but lets see those:
Try to test it under .NET 2.0 with latest .NET 2.0 service pack installed
Try to check the references in your project whether they're all clean to .NET 2.0 or not, sometimes this is not done correctly. Press F4 of every assembly that has 2.0 and 3.x versions to see properties and confirm (and remove/add if needed). If you see anything like LINQ or so, this needs to be removed.
Try to bring Visual C# 2005 Express or similar and see if the code compiles under it. Or create new .NET 2.0 project and copy your code to it.

Categories