Get single listView SelectedItem
Asked Answered
O

10

20

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. I've been using the following code...

foreach (ListViewItem item in listView1.SelectedItems)
{
    //do something with item.text or whatever
}

Because I know there will only be one item selected. What is the correct way of doing this?

Oahu answered 26/2, 2013 at 14:19 Comment(0)
S
39

Usually SelectedItems returns either a collection, an array or an IQueryable.

Either way you can access items via the index as with an array:

String text = listView1.SelectedItems[0].Text; 

By the way, you can save an item you want to look at into a variable, and check its structure in the locals after setting a breakpoint.

Shoemaker answered 26/2, 2013 at 14:23 Comment(1)
dont forget to check listView1.SelectedItems.Count to prevent null pointer exceptionMargarettmargaretta
R
18

I do this like that:

if (listView1.SelectedItems.Count > 0)
{
     var item = listView1.SelectedItems[0];
     //rest of your logic
}
Rhonarhonchus answered 26/2, 2013 at 14:23 Comment(0)
R
6

Sometimes using only the line below throws me an Exception,

String text = listView1.SelectedItems[0].Text; 

so I use this code below:

private void listView1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    if (listView1.SelectedIndices.Count <= 0) 
    { 
        return; 
    } 
    int intselectedindex = listView1.SelectedIndices[0]; 
    if (intselectedindex >= 0) 
    {
        String text = listView1.Items[intselectedindex].Text;

        //do something
        //MessageBox.Show(listView1.Items[intselectedindex].Text); 
    } 
}
Reade answered 23/10, 2014 at 10:49 Comment(0)
G
2

If its just a natty little app with one or two ListViews I normally just create a little helper property:

private ListViewItem SelectedItem { get { return (listView1.SelectedItems.Count > 0 ? listView1.SelectedItems[0] : null); } }

If I have loads, then move it out to a helper class:

internal static class ListViewEx
{
    internal static ListViewItem GetSelectedItem(this ListView listView1)
    {
        return (listView1.SelectedItems.Count > 0 ? listView1.SelectedItems[0] : null);
    }
}

so:

ListViewItem item = lstFixtures.GetSelectedItem();

The ListView interface is a bit rubbish so I normally find the helper class grows quite quickly.

Gummous answered 11/6, 2015 at 22:22 Comment(0)
M
2

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.

Mizzenmast answered 24/8, 2016 at 8:28 Comment(1)
I am really not sure this helps, where you answering a different question? For Reference - You have no check on your selected item usage thus clicking in the control while no item selected would throw an exception.Kalbli
F
0

None of the answers above, at least to me, show how to actually handle determining whether you have 1 item or multiple, and how to actually get the values out of your items in a generic way that doesn't depend on there actually only being one item, or multiple, so I'm throwing my hat in the ring.

This is quite easily and generically done by checking your count to see that you have at least one item, then doing a foreach loop on the .SelectedItems, casting each item as a DataRowView:

if (listView1.SelectedItems.Count > 0)
{
     foreach (DataRowView drv in listView1.SelectedItems)
     {
         string firstColumn = drv.Row[0] != null ? drv.Row[0].ToString() : String.Empty;
         string secondColumn = drv.Row[1] != null ? drv.Row[1].ToString() : String.Empty;
         // ... do something with these values before they are replaced
         // by the next run of the loop that will get the next row
     }
}

This will work, whether you have 1 item or many. It's funny that MSDN says to use ListView.SelectedListViewItemCollection to capture listView1.SelectedItems and iterate through that, but I found that this gave an error in my WPF app: The type name 'SelectedListViewItemCollection' does not exist in type 'ListView'.

Furthermost answered 14/11, 2016 at 14:46 Comment(0)
S
0

This works for single as well as multi selection list:

foreach (ListViewItem item in listView1.SelectedItems)
{
    int index = item.Index;
    //index is now zero based index of selected item
}
Shipping answered 1/9, 2018 at 11:1 Comment(0)
N
0
foreach (ListViewItem itemRow in taskShowListView.Items)
{
    if (itemRow.Items[0].Checked == true)
    {
        int taskId = Convert.ToInt32(itemRow.SubItems[0].Text);

        string taskDate = itemRow.SubItems[1].ToString();
        string taskDescription = itemRow.SubItems[2].ToString();            
    }
}
Nottinghamshire answered 17/11, 2019 at 14:47 Comment(0)
C
0

If you want to select single listview item no mouse click over it try this.

private void timeTable_listView_MouseUp(object sender, MouseEventArgs e)
        {
            Point mousePos = timeTable_listView.PointToClient(Control.MousePosition);
            ListViewHitTestInfo hitTest = timeTable_listView.HitTest(mousePos);



            try
            {
            int columnIndex = hitTest.Item.SubItems.IndexOf(hitTest.SubItem);
            edit_textBox.Text = timeTable_listView.SelectedItems[0].SubItems[columnIndex].Text;
            }
            catch(Exception)
            {

            }



        }
Cultural answered 3/5, 2020 at 18:45 Comment(0)
M
0

On mouse click, I would do it like this:

    public static string GetSelectedItem(ListView list)
    {
        foreach (ListViewItem item in list.Items)
        {
            if (item.Selected)
                return item.Text;
        }
        return null;
    }
Midden answered 13/11, 2022 at 19:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.