我需要填充具有文本和ID值的ComboBox(Windows窗体)。例: (“ Team1”,15) (“团队2”,27) ...
我的代码不起作用:/
List<Team> teams = new List<Team>();
teams = sq.loadTeams();
foreach (Team t in teams){
Combobox.Items.Add(t.getName(), t.getId());
}
请快点
答案 0 :(得分:0)
使用数据绑定,最好的功能是Windows窗体;)
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
可以通过组合框的Selected..
属性访问选择。
var selectedTeamId = (int)combobox.SelectedValue;
var selectedTeamName = combobox.SelectedText;
var selectedTeam = (Team)combobox.SelectedItem;
请注意,SelectedValue
和SelectedItem
返回object
类型,因此在使用前需要将其强制转换为正确的类型。