Change value in a list that is binded? - c#

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?

Related

How to make a listbox display items from a checked list and radio buttons? - C# Windows Form

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

Related comboboxes, add a third combobox

I'm trying to do a related combobox. I already have 2 comboboxes, but now I want to add a third.
I have this code for the 2nd combo box.
I'm using windows forms.
The entire code: https://repl.it/#devilonline/MuddyPartialBytecode#main.cs
private string[] GetCastById(int id)
{
return nomes.Where(line => line.movies_id== id).Select(l => l.nomes).ToArray();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox1.Items.Clear();
int id = nomes[comboBox1.SelectedIndex].id;
foreach (string name1 in GetCastById(id))
{
this.comboBox1.Items.Add(name1);
}
}
print
It is obvious that you are clearing the Items of the comboBox1 then try to get the id of the selected item, which should throw an exception because no item will be selected by then:
comboBox1.Items.Clear(); // here the items are cleared
int id = nomes[comboBox1.SelectedIndex].id; // nomes[comboBox1.SelectedIndex] = -1
Based on your database, the cast table is related to the movies so each movie has a corresponding list of cast, you should then get the id of the selected movie rather than the selected nome:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox1.Items.Clear();
int id = movies[comboBoxMovie.SelectedIndex].id; // here we used comboBoxMovie
foreach (string name1 in GetCastById(id))
{
this.comboBox1.Items.Add(name1);
}
}
This is a great opportunity to use databinding through a System.ComponentModel.BindingList<>. Below is a working example. Note, I've added get methods inside the classes for simplicity of populating the ComboBoxes for this example.
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
public class Form1
{
class Category
{
public int Id { get; set; }
public string Name { get; set; }
public Category(int id, string name)
{
this.Id = id;
this.Name = name;
}
public static List<Category> GetCategories()
{
return new List<Category>()
{
new Category(1, "Action"),
new Category(2, "Comedy")
};
}
}
class Movie
{
public int Id { get; set; }
public string Name { get; set; }
public int CategoryId { get; set; }
public Movie(int id, string name, int catId)
{
this.Id = id;
this.Name = name;
this.CategoryId = catId;
}
public static List<Movie> GetMovies()
{
return new List<Movie>()
{
new Movie(1, "Rambo", 1),
new Movie(2, "Delta Force", 1),
new Movie(3, "Elf", 2),
new Movie(4, "Space Balls", 2)
};
}
}
class Cast
{
public int Id { get; set; }
public string Names { get; set; }
public int MovieId { get; set; }
public Cast(int id, string names, int movieId)
{
this.Id = id;
this.Names = names;
this.MovieId = movieId;
}
public static List<Cast> GetCast()
{
return new List<Cast>()
{
new Cast(1, "Silvester Stalone", 1),
new Cast(2, "Chuck Norris", 2),
new Cast(3, "Will Farrell", 3),
new Cast(4, "John Candy", 4)
};
}
}
private BindingList<Category> _categoryBindingList = new BindingList<Category>();
private BindingList<Movie> _moviesBindingList = new BindingList<Movie>();
private BindingList<Cast> _castBindingList = new BindingList<Cast>();
private void Form1_Load(object sender, EventArgs e)
{
// Your database calls would replace these Get methods.
Category.GetCategories().ForEach(x => _categoryBindingList.Add(x));
Movie.GetMovies().ForEach(x => _moviesBindingList.Add(x));
Cast.GetCast().ForEach(x => _castBindingList.Add(x));
ComboBox1.DataSource = _categoryBindingList;
ComboBox1.DisplayMember = "Name";
ComboBox2.DataSource = _moviesBindingList.Where(x => x.CategoryId == (Category)ComboBox1.SelectedValue.Id).ToList();
ComboBox2.DisplayMember = "Name";
ComboBox3.DataSource = _castBindingList.Where(x => x.MovieId == (Movie)ComboBox2.SelectedValue.Id).ToList();
ComboBox3.DisplayMember = "Names";
}
private void ComboBox1_SelectedValueChanged(object sender, EventArgs e)
{
ComboBox2.DataSource = _moviesBindingList.Where(x => x.CategoryId == (Category)ComboBox1.SelectedValue.Id).ToList();
ComboBox2.DisplayMember = "Name";
ComboBox3.DataSource = _castBindingList.Where(x => x.MovieId == (Movie)ComboBox2.SelectedValue.Id).ToList();
ComboBox3.DisplayMember = "Names";
}
private void ComboBox2_SelectedValueChanged(object sender, EventArgs e)
{
ComboBox3.DataSource = _castBindingList.Where(x => x.MovieId == (Movie)ComboBox2.SelectedValue.Id).ToList();
ComboBox3.DisplayMember = "Names";
}
}

how to save value in listview from other form

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.

Remove and modify a selected item from listbox that uses datasource

I have a GUI that I am creating which reads a .csv file into a listbox and I am trying to remove a country that is selected when the application is running using a button. I have tried multiple codes however nothing works I either get a error message "Items collection cannot be modified when the DataSource property is set." or nothing happens. below is what I have at the moment. I am also trying to modify a selected item using textboxes.
namespace Countries
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private IList<tradingDetails> listOfCountries;
public class tradingDetails
{
public string Country { get; set; }
public string GDP { get; set; }
public string Inflation { get; set; }
public string TB { get; set; }
public string HDI { get; set; }
public string TP { get; set; }
public string Display
{
get
{
return string.Format("Country = {0} --- GDP = {1} --- Inflation = {2} --- TB = {3} --- HDI = {4} --- TP = {5}", this.Country, this.GDP, this.Inflation, this.TB, this.HDI, this.TP);
}
}
}
public static string[] headers { get; set; }
public void load_Click(object sender, EventArgs e)
{
this.listOfCountries = new List<tradingDetails>();
this.listBox1.ValueMember = "Countries";
this.listBox1.DisplayMember = "Display";
this.InsertInfo();
this.listBox1.DataSource = this.listOfCountries;
}
public void InsertInfo()
{
OpenFileDialog browse = new OpenFileDialog();
browse.Multiselect = true;
if (browse.ShowDialog() == DialogResult.OK)
{
string selectedFile = browse.FileName;
const int MAX_SIZE = 5000;
string[] AllLines = new string[MAX_SIZE];
AllLines = File.ReadAllLines(selectedFile);
foreach (string line in AllLines)
{
if (line.StartsWith("Country"))
{
headers = line.Split(',');
}
else
{
string[] columns = line.Split(',');
tradingDetails fileCountry = new tradingDetails
{
Country = columns[0],
GDP = columns[1],
Inflation = columns[2],
TB = columns[3],
HDI = columns[4],
TP = columns[5]
};
this.listOfCountries.Add(fileCountry);
}
}
}
}
private void DataBind()
{
listBox1.BeginUpdate();
listBox1.DataSource = listOfCountries;
listBox1.EndUpdate();
}
private void remove_Click(object sender, EventArgs e)
{
for (int x = listBox1.SelectedIndices.Count - 1; x >= 0; x--)
{
int idx = listBox1.SelectedIndices[x];
listBox1.Items.RemoveAt(idx);
}
}
private void search_Click(object sender, EventArgs e)
{
listBox1.SelectedItems.Clear();
for (int i = 0; i < listBox1.Items.Count; i++)
{
if (listBox1.Items[i].ToString().Contains(textBox1.Text))
{
listBox1.SetSelected(i, true);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox2.Text = listBox1.Items.Count.ToString();
}
}
}
UPDATE
I have tried this however this deletes all the information in the combo box and not an individual item.
private void remove_Click(object sender, EventArgs e)
{
comboBox1.DataSource = null;
comboBox1.Items.Remove(comboBox1.SelectedValue);
comboBox1.DataSource = listOfCountries;
}
You can't remove items from listbox while it's bounded with a source. For a better understanding, you are trying to remove the item, that your listbox is not an owner of, but the source is(that you have set the datasource of listbox).
Instead, you need to remove the item from the datasource itself.
private void remove_Click(object sender, EventArgs e)
{
for (int x = listBox1.SelectedIndices.Count - 1; x >= 0; x--)
{
int idx = listBox1.SelectedIndices[x];
//listBox1.Items.RemoveAt(idx);
listOfCountries.RemoveAt(idx)l
}
listBox1.RefreshItems();
}
Also, as you are trying to clear all the items from your listbox, this not a good approach to iterate every items and remove all. Instead, you should either clear your listOfCountries or set the listbox1datasource as null.

List name into variable c#

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

Categories