Get single listView SelectedItem

后端 未结 9 648
闹比i
闹比i 2020-12-01 12:39

I have the MultiSelect property of the listView set to false and I\'m trying to get a single listViewItem. But the available property is SelectedItems

9条回答
  •  青春惊慌失措
    2020-12-01 13:14

    For a shopping cart situation here's what I recommend. I'm gonna break it down into it's simplest form.

    Assuming we start with this(a list view with 2 colums, 2 buttons, and a label): starting

    First things first, removing the items, to do that we'll enter our remove button:

    private void button2_Click(object sender, EventArgs e)
    {
        listView1.Items.Remove(listView1.SelectedItems[0]);
        label1.Text = updateCartTotal().ToString();
    }
    

    Now the second line is updating our labels total using the next function i'll post to addup all the total of column 2 in the listview:

    private decimal updateCartTotal()
    {
        decimal runningTotal = 0;
        foreach(ListViewItem l in listView1.Items)
        {
            runningTotal += Convert.ToDecimal(l.SubItems[1].Text);
        }
        return runningTotal;
    }
    

    You don't have to use decimal like I did, you can use float or int if you don't have decimals. So let's break it down. We use a for loop to total all the items in the column 2(SubItems[1].Text). Add that to a decimal we declared prior to the foreach loop to keep a total. If you want to do tax you can do something like:

    return runningTotal * 1.15;
    

    or whatever your tax rate is.

    Long and short of it, using this function you can retotal your listview by just calling the function. You can change the labels text like I demo'd prior if that's what you're after.

提交回复
热议问题