Scottdg
Scottdg

Reputation: 113

C# ListBox, show multiple columns

I currently have two listboxes. One is bound to a SQL table of games. The table consists of a game_ID, Name, and Type. My listbox has a display member and value member set to Name. I want to be able to select a game and move the selected item to the second ListBox and display the Name. That part is working fine. The problem I am having is that when this is inserted into a different SQL table I want it to insert only the Game_ID (along with another sequential ID), not the Name.

The desired result would be to display only the game name in the second ListBox but still be able to use the game_id. If I have to I can display both the game_id and Name in both listboxes.

enter image description here enter image description here

the top listbox is a simple select query of the games table and the following code is used to move the items to the bottom listbox:

if (lstGames.Items.Count > 0)
        {
            lstSelGames.Items.Add(lstGames.SelectedValue);
        }

and to remove from the listbox:

if (lstSelGames.Items.Count > 0)
        {
            lstSelGames.Items.Remove(lstSelGames.SelectedItem);
        }

Upvotes: 0

Views: 1895

Answers (1)

Martin Zikmund
Martin Zikmund

Reputation: 39072

You can create a simple class with Id and Name properties and add instances of this class to the second ListBox while setting ListBox.DisplayMember to Name the same way as in the first ListBox.

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

Add item like this:

listBox.Items.Add( new Game(){ Id = 1, Name = "Some name" } );

And later retrieve:

var game = (Game)listBox.Items[0];

Upvotes: 1

Related Questions