Winforms如何使用数据源设置组合框Selectedindex?

问题描述 投票:0回答:1

我有一个类似的课程

public example class {
    public string Name {get; set;}
    public object A {get; set;}
    public object B {get; set;}
    ....
}

我有一个示例列表,我想将该列表绑定到组合框并按其名称显示。

var examples= new List<example>(){ exampleA, exampleB ,exampleC};
comboBox_ExampleSelect.DataSource = items;
comboBox_ExampleSelect.DisplayMember = "Name";

当用户选择组合框中的项目时,我可以获得所选对象

var selectedExample = comboBox_itemselect.SelectedItem;

但是当我尝试通过代码设置 SelectedItem/SelectedIndex 时,它无法工作。 我发现组合框的 itemsCollection 为空 我该怎么办?

c# winforms combobox
1个回答
0
投票

通常,通过组合框中显示的值来选择项目是很常见的。下面的 FindString 用于通过属性 Name 查找项目。如果说(与我正在使用的课程保持一致)您想通过 Id 找到,请告诉我。

注意,.DisplayMember 未设置,ToString 值用作 .DisplayMember。

public partial class StackoverflowForm : Form
{
    public StackoverflowForm()
    {
        InitializeComponent();
        // uses net8 feature to create the list, if not net8 use
        // your current method to create the list.
        List<Item> list =
        [
            new Item() { Id = 1, Name = "One" },
            new Item() { Id = 2, Name = "Two" },
            new Item() { Id = 3, Name = "Three"}
        ];

        comboBox1.DataSource = list;

        int index = comboBox1.FindString("Two");

        if (index > -1)
        {
            comboBox1.SelectedIndex = index;
        }
    }
    private void SelectedItemButton_Click(object sender, EventArgs e)
    {
        Item item = comboBox1.SelectedItem as Item;
        MessageBox.Show($"Id: {item!.Id} - {item.Name}");
    }
}
// Belongs in its own file
public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    ...
    public override string ToString() => Name;
}
© www.soinside.com 2019 - 2024. All rights reserved.