-1

I need fill a ComboBox (Windows Forms) where have a Text and ID values. Example: ("Team1", 15) ("Team2", 27) ...

My code didnt work :/

List<Team> teams = new List<Team>();
teams = sq.loadTeams();

foreach (Team t in teams){
   Combobox.Items.Add(t.getName(), t.getId());
}

heeelp please

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Gabo
  • 35
  • 4
  • Your question doesn't have enough information for us to help you. "My code didn't work" could mean anything from a compile error, to causing a nuclear explosion at your address. Please edit your question and include full details of the problem. – ProgrammingLlama Oct 22 '18 at 00:27
  • Possible duplicate of [ComboBox adding text and value](https://stackoverflow.com/questions/3063320/). – Dour High Arch Oct 22 '18 at 00:28
  • Combobox.Items.Add() does not accept two inputs! – roozbeh S Oct 22 '18 at 00:29

1 Answers1

0

Use data-binding, best feature Windows Forms come up with ;)

var list = new[]
{
    new Team { Id = 1, Name = "One" },
    new Team { Id = 2, Name = "Two" },
    new Team { Id = 3, Name = "Three" }
};

combobox.ValueMember = "Id"; // Name of property to represent a Value
combobox.DisplayMember = "Name"; // Name of property to represent displayed text.

combobox.DataSource = list; // Bind all items to the control

Selections can be accessed by Selected.. properties of combobox.

var selectedTeamId = (int)combobox.SelectedValue;
var selectedTeamName = combobox.SelectedText;

var selectedTeam = (Team)combobox.SelectedItem;

Notice that SelectedValue and SelectedItem return object type, so you need cast it to correct type before using.

Fabio
  • 31,528
  • 4
  • 33
  • 72