0

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);
        }
4
  • You need to show us the code which you used to load data and add items to ComboBox. Commented Sep 17, 2018 at 15:02
  • 1
    If you load data into DataTable and use data-binding to show data in ComboBox. Then you can easily cast the selected item of combo box to DataRowView and get other columns rather than display member. Commented Sep 17, 2018 at 15:05
  • @RezaAghaei - I have edited the post. I am not experienced with C# so I apologize if my explanation is not clear. I will look into and see if I can implement the solution from your second comment. thanks. Commented Sep 17, 2018 at 15:28
  • @RezaAghaei I was able to get the first listbox populated with the ID and the game columns using a data table. But now null exception error when trying to add it to the second listbox. Commented Sep 17, 2018 at 17:58

1 Answer 1

1

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];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.