c# windows forms link button to listview
I am using c# windows forms. I have multiple buttons linked to a listview which when a button is pressed, a new item is added to the listview. The column headers in the listview are 'Name' and 'Amount'. When a different button is pressed, a different item is added to the listview. The thing i need help with is as follows: When the same button is pressed twice, I want the amount to go from "1" to "2" on the second click. So the item na开发者_如何学Cme isnt duplicated but the amount is increase. The problem is I am using text to link the button to the linklist at the moment e.g. ("Coca Cola", "1") which adds the item name as coca cola and the amount as 1. I know it is something to do with integers so please help!!
Thanks
When the user presses a button, before adding the new row, just loop through all the current ListViewItems and check if any of them already have the same name, if so increment the amount column. Otherwise add the row as you currently do.
bool found = false;
foreach (ListViewItem item in listView1.Items)
{
if (item.Text.Equals("Coke"))
{
int amt = int.Parse(item.SubItems[1].Text);
amt++;
item.SubItems[1].Text = amt.ToString();
found = true;
}
}
if (!found)
{
ListViewItem item = listView1.Items.Add("Coke");
item.SubItems.Add("1");
}
var amount = new Dictionary<string, int>();
Button1_Click()
{
if(amount["Coca Cola"]<=0)
{
add a listview items with amount 0
}
// find the listitem with the value "Coca Cola" using FindItemWithText() Method
// set the value of ++amount["Coca Cola"] to that listitem in the amount field
}
Having a map in hand will avoid reading reading through the listview items in other scenarios.
精彩评论