adding unique items in listview
i have an ordering windows application. a product(including its quantity and price) is added to the listview when button is clicked. what i want to happen is when the product already exists in the listview, it will not add on the list but will just update the existing product info(quantity and price). how will i do this?
i have this code for adding items in the listview...
private void buttonAddItem_Click(object sender, EventArgs e)
{
ListViewItem pItem = new ListViewItem(listBoxItems.SelectedItem.ToString());
ListViewItem.ListViewSubItem sItem1 = new ListViewItem.ListViewSubItem(pItem, Convert.ToString(QuantityForm.quantity));
ListViewItem.ListViewSubItem sItem2 = new ListViewItem.ListViewSubItem(pItem, Convert.ToString(QuantityForm.quantity * Convert.ToInt16(labelItemPrice.Text)));
pItem.SubItems.Add(sItem1);
pItem.SubItems.Add(sItem2);
listViewOrders.Items.Add(pItem);
}
SimonPosted Apr 6, 2007, 5:53 PM
You probably have some sort of ID that uniquely identifies each product. You could store it in the Tag property of each ListViewItem object inside your ListView control and reference it later when trying to find the existing product.
For example, your code could be modified as such :
private void buttonAddItem_Click(object sender, EventArgs e)
{
int productID = yourCurrentProductID; // which can be saved in the listBoxItems.SelectedItem.Tag as well
ListViewItem existingItem = null;
foreach (ListViewItem item in listViewOrders.Items)
{
if ((int)item.Tag == productID)
{
existingItem = item;
break;
}
}
if (existingItem == null)
{ // the item is not already in the list, lets add it
ListViewItem pItem = new ListViewItem(listBoxItems.SelectedItem.ToString());
pItem.Tag = productID;
ListViewItem.ListViewSubItem sItem1 = new ListViewItem.ListViewSubItem(pItem, Convert.ToString(QuantityForm.quantity));
ListViewItem.ListViewSubItem sItem2 =
new ListViewItem.ListViewSubItem(pItem, Convert.ToString(QuantityForm.quantity * Convert.ToDouble(labelItemPrice.Text)));
pItem.SubItems.Add(sItem1);
pItem.SubItems.Add(sItem2);
listViewOrders.Items.Add(pItem); }
}
else
{ // the item already exists in the list
existingItem.SubItems[1].Text = Convert.ToString(QuantityForm.quantity + Convert.ToInt32(existingItem.SubItems[1].Text));
existingItem.SubItems[2].Text =
Convert.ToString((QuantityForm.quantity * Convert.ToDouble(labelItemPrice.Text)) + Convert.ToDouble(existingItem.SubItems[2].Text));
}
Hope this helps!
Simon