FutureDev
FutureDev

Reputation: 155

remove item with specific value in winforms listview

I want to remove an item in listview where its value is (for example to the pic below) equals to 100109.

enter image description here

my code is:

     private void listy()
    {
        ListViewItem lvi = new ListViewItem(dgvPOSproduct.CurrentRow.Cells[0].Value.ToString());

        lvi.SubItems.Add(dgvPOSproduct.CurrentRow.Cells[1].Value.ToString());
        lvi.SubItems.Add(lblD.Text);
        lvi.SubItems.Add(lblV.Text);
        lvi.SubItems.Add("" + dgvPOSproduct.CurrentRow.Cells[6].Value.ToString() + " x " + quantity.Text + " ");
        lvi.SubItems.Add(unittotal.Text);
        listView1.Items.Add(lvi);
    }

code to remove (which is wrong) is:

     foreach (DataGridViewRow item in this.dgvPOScart.SelectedRows)
        {
            string id = "";
            if (dgvPOScart.SelectedCells.Count > 0)
            {
                int selectedrowindex = dgvPOScart.SelectedCells[0].RowIndex;

                DataGridViewRow selectedRow = dgvPOScart.Rows[selectedrowindex];

                id = Convert.ToString(selectedRow.Cells[0].Value);

                listView1.Items[id].Remove();

            }
    }

where id value is 100109.

Upvotes: 0

Views: 1733

Answers (3)

Matt Nelson
Matt Nelson

Reputation: 991

In order for listView1.Items[id].Remove(); to work you must set the ListViewItem's Name. See the code below for the required change.

private void listy()
{
    ListViewItem lvi = new ListViewItem(dgvPOSproduct.CurrentRow.Cells[0].Value.ToString());
    lvi.Name = dgvPOSproduct.CurrentRow.Cells[0].Value.ToString(); // <---- add this line

    lvi.SubItems.Add(dgvPOSproduct.CurrentRow.Cells[1].Value.ToString());
    lvi.SubItems.Add(lblD.Text);
    lvi.SubItems.Add(lblV.Text);
    lvi.SubItems.Add("" + dgvPOSproduct.CurrentRow.Cells[6].Value.ToString() + " x " + quantity.Text + " ");
    lvi.SubItems.Add(unittotal.Text);
    listView1.Items.Add(lvi);
}

Upvotes: 1

jason.kaisersmith
jason.kaisersmith

Reputation: 9610

One option is to build a helper function to find the item index you require.

private int findIndexForItem(string name)
{
    int ind = -1;
    for (int i = 0; i < listView1.Items.Count; i++)
    {
        if (listView1.Items[i].Text.Equals(name))
        {
            ind = i;
            break;
        }
    }
    return ind;
}

Then call it such as this

int ind = findIndexForItem("100109");
if (ind >= 0)
    listView1.Items.RemoveAt(ind);

Upvotes: 1

Rebin Qadir
Rebin Qadir

Reputation: 311

You can use the following simple way I have putted the loop inside a button event.

private void button1_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem Item in listView1.SelectedItems)
            {
                listView1.Items.Remove(Item);
            }
        }  

Upvotes: 0

Related Questions