Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Tie ListView items with objects

Whats the best way to tie ListView item with a object so when i move the item form one listview to another then i would be still able to tell to what object its assigned. For example, i have object Cards. All these are listed in a allCards ListView. I have another selectedCards ListView and a button what moves selected items from one listview to another. When im done my selection i need to get the list of the Card objects what moved to the selectedCards ListView.

like image 350
hs2d Avatar asked May 31 '11 13:05

hs2d


1 Answers

To expand on @CharithJ's answer, this is how you would use the tag property:

    ListView allCardsListView = new ListView();
    ListView selectedCardsListView = new ListView();
    List<Card> allCards = new List<Card>();
    List<Card> selectedCards = new List<Card>();
    public Form1()
    {
        InitializeComponent();


        foreach (Card selectedCard in selectedCards)
        {
            ListViewItem item = new ListViewItem(selectedCard.Name);
            item.Tag = selectedCard;
            selectedCardsListView.Items.Add(item);
        }
        foreach (Card card in allCards)
        {
            ListViewItem item = new ListViewItem(card.Name);
            item.Tag = card;
            allCardsListView.Items.Add(new ListViewItem(card.Name));
        }

        Button button = new Button();
        button.Click += new EventHandler(MoveSelectedClick);
    }

    void MoveSelectedClick(object sender, EventArgs e)
    {
        foreach (ListViewItem item in allCardsListView.SelectedItems)
        {
            Card card = (Card) item.Tag;
            //Do whatever with the card
        }
    }

Obviously you'll need to adapt it to your own code, but that should get you started.

like image 133
Davy8 Avatar answered Oct 20 '22 06:10

Davy8