how can I know which Item was selected in listview + imagelist

301 Views Asked by At

This is the fist time I post a question on this site and I need some help. This is my code

private void loadMatrixOfTables()
{
    try
    {
        var tb = BaSic.db.tb_Tables; //load database with LINQ
        lsvTables.Clear(); //this is my lisview

        foreach (var b in tb)
        {
            if (b.Status == true)
            {
                lsvTables.Items.Add(b.Name,1);
            }
            else
            {
                lsvTables.Items.Add(b.Name, 0);
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: " + ex.ToString());
    }
}

My table has 2 fields: id and name What I need do to get item value, not item text.

1

There are 1 best solutions below

1
On BEST ANSWER

I don't know the type of b so the example is using the 2 known attributes id and string assuming that are an int and a string respectively . Just change them for your containing class.

First you need to create your own ListViewItem, to support show the name on the listView and get his id when is required. In your case it looks like this:

public class CustomListViewItem : ListViewItem
{
    public CustomListViewItem(int id,  string name)
    {
        Id = id;
        Name = name;
    }

    public int Id { get; set; }
    public string Name { get; set; }
}

Using it

First create your item

var item = new CustomListViewItem(id, name)

To show in the listview the name just add:

item.Text = name

and then added to the listView:

lsvTables.Items.Add(item,1)

To retrieve the selected item's id just cast the selected item as CustomListViewItem. For example:

int id = (CustomListViewItem)lsvTables.SelectedItems[0].Id;