i'm very new as you can see in my programming, i'm making a simple program excercise. I would like to put for example the Item.price & Item.Name into Listbox2.
is it possible to put the arrayName into a variable and put it in a foreach loop?
Just to prevent a very long IF loop or switch, or a while loop.
For example :
Array variable = Drinks;
foreach(Product item in VARIABLE)
{
listBox2.Items.Add(item.ProductName + item.Price);
}
Ps: i already tryed with a temporary List where you put the drinkList into the Temporary list and then call it the product.Name and/or Product.price.
public partial class Form1 : Form
{
List<Product> Drinks = new List<Product>() {new Product("Coca Cola", 1.2F), new Product("Fanta", 2.0F), new Product("Sprite", 1.5F) };
List<Product> Bread = new List<Product>() { new Product("Brown Bread", 1.2F), new Product("White Bread", 2.0F), new Product("Some otherBread", 1.5F) };
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox1.Items.Clear();
if (comboBox1.Items.IndexOf(comboBox1.SelectedItem) == 0)
{
foreach (Product item in Drinks)
{
listBox1.Items.Add(item.ProductName);
}
}
else
{
foreach (Product item in Bread)
{
listBox1.Items.Add(item.ProductName);
}
}
}
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
// do something here
}
}
public class Product
{
private string productName;
private float price;
public Product(string productName, float price)
{
this.ProductName = productName;
this.Price = price;
}
public string ProductName
{
get { return productName; }
set { productName = value; }
}
public float Price
{
get { return price; }
set { price = value; }
}
}
I'm not sure what you are looking for exactly but maybe you could put the type of product (drink or bread) in the struct?
public struct Products
{
public string type;
public string name;
public double price;
}
You can then create the list
List<Products>
and use it in your foreach loop as you did in your example
It sounds like what you're looking for is:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox1.Items.Clear();
// start with Bread and change if necessary.
List<Product> products = Bread;
if (comboBox1.Items.IndexOf(comboBox1.SelectedItem) == 0)
{
//change the value of "products"
products = Drinks;
}
foreach (Product item in products)
{
listBox1.Items.Add(item.ProductName + item.Price);
}
}
Related
I'm doing a project where I am trying to simulate an ice cream parlor. For this specific section, I have the (mutually exclusive) radio buttons representing the dressing the customer can select. There are also a number of checked items (not mutually exclusive) which the customer can select in the checkedListBox. All of the items that a customer selects from the radio buttons and checkedListBox are supposed to appear in a listbox. so that the customer can keep track of all of the ordered items.
Of course, all of the code here is very unfinished and basic. I don't plan on adding any of the calculations for the prices until I make sure that the structure itself is working.
This is what I currently have so far:
private void GetToppings()
{
foreach (ListViewItem li in checkedListBox1.Items)
{
if (li.Selected == true)
{
label1.Text += li + " ";
}
}
if (checkedListBox1.SelectedItem.ToString() == "Sprinkles")
{
}
if (checkedListBox1.SelectedItem.ToString() == "Chocolate Chips")
{
}
if (checkedListBox1.SelectedItem.ToString() == "M&Ms")
{
}
if (checkedListBox1.SelectedItem.ToString() == "Oreos")
{
}
if (checkedListBox1.SelectedItem.ToString() == "Cookie Dough")
{
}
private void GetDressing()
{
if (radioButton1.Checked)
{
sDressing += "Caramel";
}
if (radioButton2.Checked)
{
sDressing += "Hot Fudge";
}
if (radioButton3.Checked)
{
sDressing += "Peanut Butter";
}
if (radioButton4.Checked)
{
sDressing += "Strawberry Syrup";
}
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i<18; i++)
{
listBox1.Items.Add(i);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox1.Items.Remove(listBox1.SelectedItem);
}
I am still very new to Windows Form programming in C#, so please forgive me if any of these questions/errors seem very basic.
The RadioButton use the following
var radioButton = Controls.OfType<RadioButton>().FirstOrDefault(x => x.Checked);
if (radioButton is not null)
{
// do something
}
For the CheckedListBox consider the following which populates via a model/class which has text and a identifier as in most cases at a later date you work with a data source this is important to keep track of items which you are not there yet but best to do it just the same.
Extension method to get items in the CheckedListBox. Place in a class file.
public static class CheckedListBoxExtensions
{
public static List<T> CheckedList<T>(this CheckedListBox sender)
=> sender.Items.Cast<T>()
.Where((_, index) => sender.GetItemChecked(index))
.Select(item => item)
.ToList();
}
Use a class/model for populating the CheckedListBox, ToString is used to display the item. Place in a class file.
public class Topping
{
public int Id { get; set; }
public string Name { get; set; }
public override string ToString() => Name;
}
Implementation
public partial class StackOverflowForm : Form
{
public StackOverflowForm()
{
InitializeComponent();
List<Topping> toppings = new List<Topping>
{
new Topping() { Id = 1, Name = "Sprinkles" },
new Topping() { Id = 2, Name = "Chocolate Chips" },
new Topping() { Id = 3, Name = "M&Ms" },
new Topping() { Id = 4, Name = "Oreos" },
new Topping() { Id = 5, Name = "Cookie Dough" }
};
checkedListBox1.DataSource = toppings;
}
private void GetToppingsButton_Click(object sender, EventArgs e)
{
List<Topping> toppings = checkedListBox1.CheckedList<Topping>();
if (toppings.Count > 0)
{
listBox1.DataSource = toppings;
}
else
{
listBox1.DataSource = null;
}
}
}
I'm pretty new at this. Using Windows Forms in Visual Studio. I am to hammer out a store that has clothes, with stock that can be transferred in or out of the store.
I've gotten as far as to having a class, a list that contains the clothes and their quantities, and I've managed to get them into comboboxes. What I want to do now is to be able to 'buy' new quantities, changing the value in the list.
I'm stumped as to how to change the actual quantities, I'm sure I am missing stuff here.
This is my class:
public class Store
{
public string Clothing { get; set; }
public int Quantity { get; set; }
public Store(string c, int q)
{
Clothing = c;
Quantity = q;
}
And this is my current code:
}
public partial class Form1 : Form
{
List<Store> stock = new List<Store>
{
new Store ("Jeans size S", 1),
new Store ("Jeans size M", 3),
new Store ("Jeans size L", 5)
};
public Form1()
{
InitializeComponent();
}
private void bShow_Click(object sender, EventArgs e)
{
cbStockType.ValueMember = "Clothing";
cbStockType.DisplayMember = "Clothing";
cbStockType.DataSource = stock;
cbStockQnt.ValueMember = "Quantity";
cbStockQnt.DisplayMember = "Quantity";
cbStockQnt.DataSource = stock;
}
private void lblHighlightAdd_Click(object sender, EventArgs e)
{
}
private void bSlctClothing_Click(object sender, EventArgs e)
{
if (cbStockType.SelectedIndex < 0)
{ lblHighlightAdd.Text = "None"; }
else
lblHighlightAdd.Text = cbStockType.SelectedValue.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
string quantityToAdd = tbQntAdd.Text;
int add = Convert.ToInt32(quantityToAdd);
string addToStock = cbStockQnt.SelectedValue.ToString();
int newAmount = Convert.ToInt32(addToStock);
int result = newAmount + add;
foreach (var item in stock)
{
if (item.Clothing == cbStockType.SelectedValue.ToString())
{
item.Quantity = item.Quantity + result;
MessageBox.Show(cbStockQnt.SelectedValue.ToString());
}
}
}
}
}
If you can read this spaghetti junk, I'm stuck at getting the quantity of the selected piece of clothing to change. How do I get it to change the value both in the list and in the combobox?
Im having a problem in my listview because whenever I get value in other form it is not adding on the list but when I put breakpoint it have a value but still not adding on my listview.
here is my function in form1 getting values from datagridview
public void dataGridView1_DoubleClick(object sender, EventArgs e)
{
qtyOfOrders orders = new qtyOfOrders();
if (dataGridView1.SelectedRows.Count > 0)
{
String mealname = dataGridView1.SelectedRows[0].Cells[1].Value + String.Empty;
String price1 = dataGridView1.SelectedRows[0].Cells[2].Value + String.Empty;
pts.meal = mealname;
pts.qtyprice = Int32.Parse(price1);
orders.Show();
}
}
here is my function from form2 and will save data in listview in form1
private void OK_Click(object sender, EventArgs e)
{
cashier c = new cashier();
pricetempstorage pts = new pricetempstorage(); //class
int qty = Int32.Parse(QTYNumber.Text);
int totalPrice = qty * pts.qtyprice;
pts.qtynumber = qty;
pts.TotalPrice = totalPrice;
c.listView1.Items.Add(pts.meal);
c.qtyOrder.ListView.Items[0].SubItems.Add(pts.qtynumber.ToString());
c.price111.ListView.Items[0].SubItems.Add(pts.TotalPrice.ToString());
this.Hide();
}
this is my class
namespace jollibee4
{
class pricetempstorage
{
static int qtyNumber;
static int qtyPrice;
static int ListViewCount;
static String Meal;
static int totalprice;
public int TotalPrice
{
get
{
return totalprice;
}
set
{
totalprice = qtyNumber * qtyPrice;
}
}
public int qtynumber
{
get
{
return qtyNumber;
}
set
{
qtyNumber = value;
}
}
public int qtyprice
{
get
{
return qtyPrice;
}
set
{
qtyPrice = value;
}
}
public int listviewCount
{
get
{
return ListViewCount;
}
set
{
ListViewCount = value;
}
}
public String meal
{
get
{
return Meal;
}
set
{
Meal = value;
}
}
}
}
Try adding this code this.listView1.View = View.Details; After the c.listView1.Items.Add(pts.meal);
form1
public List<pricetempstorage> Items { get; private set; }
private void OK_Click(object sender, EventArgs e)
{
cashier c = new cashier();
pricetempstorage pts = new pricetempstorage(); //class
int qty = Int32.Parse(QTYNumber.Text);
int totalPrice = qty * pts.qtyprice;
pts.qtynumber = qty;
pts.TotalPrice = totalPrice;
Items.Add(pts);
this.Hide();
}
Create a shopping cart class where items can be append in list
I assume pricetempstorage is your class of item, its name can be product
public static ShoppingCart GetInstance()
{
if (cart == null)
{
cart = new ShoppingCart();
}
return cart;
}
protected ShoppingCart()
{
Items = new List<pricetempstorage>();
}
You have many architectural and stylistic issues with your program (use of static, capitalization, etc.)--to correct them all would require a very lengthy response.
Your code isn't working because you're creating a new instance of the cashier class, and then you're updating its listView1 object. What I think you're trying to do is update the listView object of Form2. So what you should be doing is grabbing a reference to Form2 and populating its ListView object in your OK_Click event handler...
Just a tip here: Public properties should have an initial capital letter. Your pricetempstorage class needs some work.
how to update e specific value on a list..
for example when i click a button it adds the product on the list
name: coffe || quantity:1 || Price:2$
and when i click angain the same product the quantity increases by 1
i used this code but it doesnt change the number of the quantity.
private BindingList<recipt> Lista2 = new BindingList<recipt>();
private void addtolist(object sender, EventArgs e)
{
Button b = (Button)sender;
Product p = (Product)b.Tag;
recipt fat = new recipt ()
{
Name= p.Name,
quantity= 1,
price = p.Cmimi
};
bool found = false;
if (listBox1.Items.Count > 0)
{
foreach (var pr in Lista2)
{
if (pr.Name== p.Name)
{
pr.quantity= pr.quantity+ 1;
found = true;
}
}
if (!found)
{
fat.tot= fat.quantity* fat.price;
fat.Nr_bill = Convert.ToInt32(txtNrbill.Text);
Lista2.Add(fat);
}
}
else
{
fat.tot= fat.quantity* fat.price;
fat.Nr_bill = Convert.ToInt32(txtNrbill.Text);
Lista2.Add(fat);
}
fat.tot= fat.quantity* fat.price;
fat.Nr_bill = Convert.ToInt32(txtNrbill.Text);
Lista2.Add(fat);
pe.Faturs.Add(fat);
pe.SaveChanges();
Total = Total + (int)fat.price;
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
For updating values in ListBox automatically you need set BindingList of receipts to the ListBox.DataSource and make Receipt class implement INotifyPropertyChanged
public class Receipt : INotifyPropertyChanged
{
public string Name { get; }
public int Quantity { get; private set; }
public decimal Price { get; }
public string BillNumber { get; private set; }
public decimal Total => Price * Quantity;
public string Info => $"{nameof(Name)}: {Name} || {nameof(Quantity)}: {Quantity} || {nameof(Price)}: {Price:C} || {nameof(Total)}: {Total:C}";
public Receipt(string name, decimal price, string billNumber)
{
Name = name;
Price = price;
BillNumber = billNumber;
Quantity = 1;
}
public void AddOne()
{
Quantity += 1;
RaisePropertyChanged(nameof(Info));
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Then in the form
public class YourForm : Form
{
private readonly BindingList<Receipt> _Receipts;
public YourForm()
{
_Receipts = new BindingList<Receipt>();
listBox1.DisplayMember = "Info";
listBox1.DataSource = _Receipts;
}
private void AddToList(object sender, EventArgs e)
{
var button = (Button) sender;
var product = (Product) button.Tag;
var receiptInfo = _Receipts.FirstOrDefault(receipt => receipt.Name.Equals(product.Name));
if (receiptInfo == null)
{
receiptInfo = new Receipt(product.Name, product.Cmimi, txtNrbill.Text);
_Receipts.Add(receiptInfo);
}
else
{
receiptInfo.AddOne();
}
}
}
I've got an application I'm building that inputs data into a list, using input textboxes on one tab (say Tab 1). When you hit the command button it adds the data (Book number, author, title, genre, # of pages and Publisher) to a list (books).
It then displays the title of the book in a listbox on tab 2. When you click the item in the listbox on tab 2, I want it to redisplay all the information you just input on tab 1, into textboxes on tab 2. But I can't get information to show up.
Below is my code, including the class I created for the project.
class Book
{
//attributes
private string callNumber;
private string bookTitle;
private string authorName;
private string genre;
private int numberOfPages;
private string publisher;
//constructor
public Book()
{
}
//accessor
public void SetNumber(string aNumber)
{
callNumber = aNumber;
}
public void SetTitle(string aTitle)
{
bookTitle = aTitle;
}
public void SetAuthor(String aName)
{
authorName = aName;
}
public void SetGenre(String aGenre)
{
genre = aGenre;
}
public void SetPages(int aPageNumber)
{
numberOfPages = aPageNumber;
}
public void SetPublisher(String aPublisher)
{
publisher = aPublisher;
}
public string GetNumber()
{
return callNumber;
}
public string GetTitle()
{
return bookTitle;
}
public string GetAuthor()
{
return authorName;
}
public string GetGenre()
{
return genre;
}
public int GetPages()
{
return numberOfPages;
}
public string GetPublisher()
{
return publisher;
}
}
public partial class Form1 : Form
{
List<Book> books;
public Form1()
{
InitializeComponent();
this.books = new List<Book>();
}
private void btnAdd_Click(object sender, EventArgs e)
{
Book aBook = new Book();
aBook.SetNumber(txtCallNumber.Text);
aBook.SetAuthor(txtAuthorName.Text);
aBook.SetTitle(txtBookTitle.Text);
aBook.SetGenre(txtGenre.Text);
aBook.SetPages(int.Parse(txtNumberOfPages.Text));
aBook.SetPublisher(txtPublisher.Text);
foreach (Control ctrl in this.Controls)
{
if (ctrl is TextBox)
{
((TextBox)ctrl).Clear();
}
txtCallNumber.Focus();
txtAuthorName.Clear();
txtBookTitle.Clear();
txtCallNumber.Clear();
txtGenre.Clear();
txtNumberOfPages.Clear();
txtPublisher.Clear();
lstLibrary.Items.Add(aBook.GetTitle());
}
}
private void lstLibrary_SelectedIndexChanged(object sender, EventArgs e)
{
int index = 0;
foreach (Book book in books)
{
string tempTitle;
tempTitle = book.GetTitle();
if (tempTitle == (string)lstLibrary.SelectedItem)
break;
else
{
index++;
}
txtNumberRecall.Text = books[index].GetNumber();
txtTitleRecall.Text = books[index].GetTitle();
txtAuthorRecall.Text = books[index].GetAuthor();
txtGenreRecall.Text = books[index].GetGenre();
txtPagesRecall.Text = Convert.ToString(books[index].GetPages());
txtPublisherRecall.Text = books[index].GetPublisher();
break;
}
}
}
}
Once again, I'm trying to get the information from the listbox (in the click event) to show up in the textboxes.
Will something like this work?
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
foreach (string s in listBox1.Items)
{
i++;
if (i == 1)
{
textBox1.Text = s;
}
if (i == 2)
{
textBox2.Text = s;
}
if (i == 3)
{
textBox3.Text = s;
}
}
}
In the btnAdd_Click method, you are never saving the new aBook that you created. You need to add it to you books collection. Adding the title as an entry in lstLibrary.Items does not actually save the newly created object.
Also, you should review your looping structures. In btnAdd_Click() it looks like you will add it to lstLibrary once for each control that exists on your form. In lstLibrary_SelectedIndexChanged(), if you had actually added books to the collection in btnAdd_Click(), you would update the textboxes for the first book in the collection that does not match the selected book.