Need help appending a variable in listbox - c#

When the Add button is pressed the price is taken from the second half of a 'split' line in the first list box. This is then multiplied by a value entered in a textbox or just entered as is into the second listbox.
I have then added a line below it in the second list box with the total price. When a new item is added the code removes the previous total price and replaces it with the new updated total price.
I'm looking to then append (add all the prices being listed in the second listbox) the prices together in the 'total price' section of the last line of the second list box.
Below is the code I have written so far.
private void button1_Click(object sender, EventArgs e)
{
string TheItem = Convert.ToString(listBox1.SelectedItem);
string[] theSplits = TheItem.Split(' ');
string FirstSplit = theSplits[0];
string SecondSplit = theSplits[1];
Decimal theNewTotal;
Decimal theValue;
if (textBox1.Text == "")
{
listBox2.Items.Add(TheItem);
listBox2.Items.Add("Total Price:" + SecondSplit);
}
else
{
theValue = Convert.ToDecimal(SecondSplit) * Convert.ToDecimal(textBox1.Text);
listBox2.Items.Add(textBox1.Text + "x " + TheItem);
theNewTotal = theValue;
listBox2.Items.Add("Total Price:" + theNewTotal);
}
if (listBox2.Items.Count > 2)
{
int theNumber = listBox2.Items.Count;
listBox2.Items.RemoveAt(theNumber-3);
}
}

You'd be better off starting by removing the total price first, as you expend some effort trying to work around that. So something like:
private void button1_Click(object sender, EventArgs e) {
RemoveLastTotal();
AppendPrices();
AppendTotal();
}
private void RemoveLastTotal() {
var lastItemIndex = listBox2.Items.Count-1;
if (listBox2.Items[lastItemIndex].StartsWith("Total Price:"))
{
listBox2.Items.RemoveAt(lastItemIndex);
}
}
private void AppendPrices() {
string TheItem = Convert.ToString(listBox1.SelectedItem);
string[] theSplits = TheItem.Split(' ');
string itemDesc = theSplits[0];
string itemPrice = theSplits[1];
float quantity = (string.IsNullOrEmpty(textBox1.Text))? 0: float.Parse(textBox1.Text)
if (quantity==0) {
listBox2.Items.Add(TheItem);
} else {
var lineTotal = Convert.ToDecimal(itemPrice) * quantity;
listBox2.Items.Add(textBox1.Text + " x " + TheItem + " = " + lineTotal);
}
}
private void AppendTotal()
{
var total = 0;
foreach(var item in listBox2.Items)
{
var splits = item.Split(' ');
total += decimal.parse(splits[splits.length-1]);
}
listBox2.Items.Add("Total Price:" + total);
}
That said, if you really want to do it "properly", you should separate the view i.e. the listbox from the model (DataTable for instance).

Related

How to join same lines in textbox and count them

Hey Guys I have Problem I have a textbox who will have sometimes same lines now I need to count them and show the number in joined line with the text
private void textBox1_TextChanged(object sender, EventArgs e)
{
string[] same =textBox1.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None).Distinct().ToArray();
textBox1.Text = string.Join("\r\n", same);
}
in this code it will join the lines and I am able to see just one line but I need a count of lines and if I have some number in that line to count that also
for example:
Earth 2
Water
Air
Earth
Expected :
Earth x2 4
Water
Air
Your question is a bit confusing, BTW I solve it this way.
First I made a class for each result item
Result Class
public class Result
{
public string Item{ get; set; }
public int Count{ get; set; }
public int Value{ get; set; }
}
Then I have a button to translate the 'user input' to the desired format
You can run this method as textbox1_changed
Button Translate Clicked Method
private void btnTranslate_Click(object sender, EventArgs e)
{
var items = textBox1.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None).ToList();
var results = new List<Result>();
foreach (var item in items)
{
var text = item;
var value = 0;
var row = item.Split(' ').ToList();
if (row.Count == 2) // item contains value like: Earth 2
{
text = row[0];
Int32.TryParse(row[1], out value);
}
var result = results.FirstOrDefault(r => r.Item.Equals(text));
if (result == null) // first time item apears in the list
{
result = new Result
{
Item = text,
Count = 1,
Value = value
};
results.Add(result);
}
else // item added before should increase the count
{
result.Count++;
result.Value += value;
}
}
textBox2.Text = Prettify(results); // lets make the result pretty
}
In the end I declared Prettify function to make the result as you wanted
Prettify Method
public string Prettify(List<Result> results)
{
var prettify = "";
int row = 0;
foreach (var result in results)
{
prettify += $"{++row}. {result.Item}"; // 1. Earth
if (result.Count > 1)
prettify += $" x{result.Count}"; // 1. Earth x2
if (result.Value > 0)
prettify += $" {result.Value}"; // 1. Earth x2 4
prettify += Environment.NewLine;
}
return prettify;
}
Here is the output
Output
I guess the core is right, you could customize it
Have fun

How to modify an item inside ListBox?

i want to concat(add) a string over an existing item here is the code:
private void button4_Click(object sender, EventArgs e)
{
double total = 0;
double[] prices = {0.5, 1.0, 1.5, 3.0, 2.5, 2.0};
CheckBox[] boxes = { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6 };
listBox2.Items.Add(textBox1.Text + " : ");
for (int i=0;i<boxes.Length ;i++)
{
if (boxes[i].Checked==true)
{
total += prices[i];
listBox2.Items.Add(boxes[i].Text+" "); //it adds a new item
}
}
the problem is with the output , every time it adds a new item i just want to add this line boxes[i].Text+" " , to the same item
thank you.
What do you mean by:
to the same item
Do you want to add it all to this one? listBox2.Items.Add(textBox1.Text + " : ");
If so could you not just do this:
string name = textBox1.Text + " : ";
for (int i=0; i < boxes.Length; i++)
{
if (boxes[i].Checked == true)
{
total += prices[i];
name += boxes[i].Text + " ";
}
}
listBox2.Items.Add(name);
You should use the following command listbox2.items[0]+=boxes[i].Text+" " with 0 being the index of the item you want to concatenate the string with.Because listbox2.items.Add will just keep adding items to your Listbox.
Best Regards.

Logical error in display/math not displaying initial result

I have a population estimator program for school, the results do not display the first set of results. Here is the code.
private void Button1_Click(object sender, EventArgs e)
{
double startingPop;
double increasePer;
double numDays;
const int INTERVAL = 1;
if (double.TryParse(textBox1.Text, out startingPop))
{
if (double.TryParse(textBox2.Text, out increasePer))
{
if (double.TryParse(textBox3.Text, out numDays))
{
for (int i = 1; i <= numDays; i += INTERVAL)
{
startingPop = (startingPop * (increasePer / 100) + startingPop);
Results.Items.Add("After " + i + " days, the amount of organisms is " + startingPop);
}
}
}
}
}
private void Button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void Button3_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
Results.Items.Clear();
}
I want it to show day 1 2 organisms, instead it shows the first calculation with the increase percentage i.e (day 1 2.6). I know this is probably super obvious so I apologize. Thanks for your insight.
If I understand your problem correctly, your code should look something like this:
private void button1_Click(object sender, EventArgs e)
{
double startingPop;
double increasePer;
double numDays;
const int INTERVAL = 1;
if (double.TryParse(textBox1.Text, out startingPop) &&
double.TryParse(textBox2.Text, out increasePer) &&
double.TryParse(textBox3.Text, out numDays))
{
Results.Items.Add("On the first day, the amount of organisms is " + startingPop);
for (int i = 1; i <= numDays; i += INTERVAL)
{
startingPop = (startingPop * (increasePer / 100) + startingPop);
Results.Items.Add("After " + i + " day(s), the amount of organisms is " + startingPop);
}
}
}
The changes I made to the code:
Combine the three if statements into one using the && operator.
Print the population value before increasing it so that the next displayed value (which reads "after 1 day") will be the next incremented value.
To make your result items grammatically correct, you may the second line inside the loop with something like:
string s = (i > 1 ? "s" : string.Empty);
Results.Items.Add($"After {i} day{s}, the amount of organisms is {startingPop}.");
Now, assuming the values in textBox1, textBox2, textBox3 are 2, 30, and 5, the displayed result would be something like this:

How to make a condition out of the selected listbox item?

I can't believe I got drained by this small problem trying to find the solution playing with the intellisense. No luck Just starting c# GUI. Just need a quick answer please.
if (listBox1.SelectedValue== "Chicken")
{
total += 15;
ord += " Chicken";
label4.Text = "chicken selected";
}
what the hell is wrong with this.
I want to execute the statements when the user selected the item "chicken" from listbox1.
public partial class Form1 : Form
{
double total = 0;
int x = 0;
string ord = "";
private void placeToolStripMenuItem_Click(object sender, EventArgs e)
{
checkBox1.Checked = false;
radioButton1.Checked = false;
radioButton2.Checked = false;
radioButton3.Checked = false;
radioButton4.Checked = false;
listBox1.SelectedItems.Clear();
if (checkBox1.Checked)
{
total += 1;
ord += " Water";
}
if (checkBox1.Text == "Extra Meat")
{
total += 1;
ord += ord+" Extra Meat ";
}
if (comboBox1.Text == "Extra Rice")
{
total += 1;
ord += " Extra Rice";
}
if (comboBox1.Text == "Extra Veggies")
{
total += 1;
ord +=" Extra Veggies";
}
if (listBox1.SelectedValue== "Chicken")
{
total+=15;
ord+=" Chicken";
label4.Text = "chicken selected";
}
if (listBox1.Text == "Pizza $8") //< my pathetic attempt to figure it out with intelisense
{
total+=8;
ord+="Pizza ";
label4.Text = "qwe";
}
if (listBox1.SelectedItem == "Spaghetti $12")//< my pathetic attempt to figure it out with intelisense
{
total+=12;
ord+=" Spaghetti";
}
if (listBox1.SelectedItem == "Fries $8")
{
total+=8;
ord+=" Fries";
}
if (listBox1.SelectedItem == "Burger $10")
{
total+=10;
ord+=" Burger";
}
//radiobutton
if (radioButton1.Checked)
{
total+=5;
ord += " Pineapple Juice";
}
if (radioButton2.Checked)
{
total+=6;
ord += " Mango Juice";
}
if (radioButton3.Checked)
{
total+=7;
ord += " Apple Juice";
}
if (radioButton4.Checked)
{
total+=8;
ord += " Orange Juice";
}
MessageBox.Show("Order Done");
}
private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
ord = "";
total = 0;
}
private void displayToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Order: " + ord+"\nTotal: "+total);
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
}
You code cannot work, since you clear all the selections before you are processing the order. Move this code to the very end of the placeToolStripMenuItem_Click method:
// Process the order here ...
MessageBox.Show("Order Done");
checkBox1.Checked = false;
radioButton1.Checked = false;
radioButton2.Checked = false;
radioButton3.Checked = false;
radioButton4.Checked = false;
listBox1.SelectedItems.Clear();
I think that your approach is wrong. You should not have to make all these if-statements. Instead create a Product class
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public override ToString()
{
return String.Format("{0} ${1}", Name, Price);
}
}
Then add products to your listbox:
listbox1.Items.Add(new Product{ Name = "Chicken", Price = 15 });
listbox1.Items.Add(new Product{ Name = "Pizza", Price = 8 });
...
Then you can work with the selected item like this:
var product = listBox1.SelectedItem as Product;
if (product != null) {
total += product.Price;
ord += " " + product.Name;
label4.Text = product.Name + " selected";
}
Also declare total as decimal. Doubles are good for scientific calculations, but can easily yield results like 7.49999999 instead of 7.5. Decimals have been introduced especially for currency calculations. They are not very fast but they don't convert decimal numbers into binary numbers internally, instead the decimal digits are preserved. The problem with binary numbers is that for instance 1/10 cannot be represented accurately just like 1/3 cannot be represented accurately in the decimal system.
You can even add products to your radio buttons
radioButton3.Tag = new Product{ Name = "Apple Juice", Price = 7 };
A more advanced method would be to create your own radio button control with a Product property, but this solution will do it for now.
Then you can loop through all your radio buttons like this
foreach (var radioButton in Controls.OfType<RadioButton>()) {
if (radioButton.Checked) {
var p = (Product)radioButton.Tag;
total += p.Price;
ord += " " + p.Name;
}
}
You need to use SelectedItem.
if (listBox1.SelectedItem == "Chicken")
My program is throwing a Nullreferenceexception on me.
on this line:
if (listBox1.SelectedItem.ToString() == "Chicken $15")
I have to initialize it i guess but i have no idea how to initialize a listBox.
First Method:
if (listBox1.SelectedIndex != -1) //first check if any item is selected
if (listBox1.SelectedItem.ToString() == "Chicken")
Second Method:
if (listBox1.Text == "Chicken")
and just remove the line:
private void placeToolStripMenuItem_Click(object sender, EventArgs e)
{
listBox1.SelectedItems.Clear(); //remove this line
It clears your selected items, that's why you are not getting into any if condition.

listbox selection update textbox

Need to update 3 text boxes with decimals, after selecting an item in a Listbox.
link to files: https://www.dropbox.com/s/xj2efe5sxsolswk/midterm.zip
Format in listbox: "Name |XX| |XX| |XX|" e.g. "Matt |100| |90| |80|"
How do I recall the 3 values associated with a selected index from the listbox, to calculate 3 values and update 3 text boxes, associated with that listbox selection?
I have created 3 lists to attempt to store what I need. I am saving the score inputs to scoreList2, but not sure how to link them when associating it with the ListBox.
public static List<string> scoreList = new List<string>();
public static List<decimal> scoreList2 = new List<decimal>();
public static List<object> scoreList3 = new List<object>();
Code:
private void Form1_Load(object sender, EventArgs e)
{
(all hard coded cuz I'm a noob)
//txtScoreTotal.Text = tempNum1.ToString();
//txtScoreTotal.text =
//txtScoreCount.Text = tempNum2.ToString();
//txtAverage.Text = tempNum3.ToString();
lbStudents.Items.Add(tempInfo1 + " " + tempNum1 + " " + tempNum2 + " " + tempNum3);
}
private void lbStudents_SelectedIndexChanged(object sender, EventArgs e)
{
/*
txtScoreTotal.Text = tempNum1.ToString();
//txtScoreTotal.Text = selected listbox scoretotal
txtScoreCount.Text = tempNum2.ToString();
//txtScoreTotal.Text = selected listbox scorecount
txtAverage.Text = tempNum3.ToString();
//txtSCoreTotal.Text = selected listbox average
*/
txtScoreTotal.Text = lbStudents.SelectedItem.ToString();
}
You can use String.Split method and LINQ like this:
private void lbStudents_SelectedIndexChanged(object sender, EventArgs e)
{
if(lbStudents.SelectedItem != null)
{
decimal result;
var numbers = lbStudents.SelectedItem.ToString()
.Split(new [] { '|' }, StringSplitOptions.RemoveEmptyEntries)
.Where(x => decimal.TryParse(x, out result))
.ToList();
txtBox1.Text = numbers[0];
txtBox2.Text = numbers[1];
txtBox3.Text = numbers[2];
}
}

Categories

Resources