【问题标题】:Set Combobox value from id of the set using Data Bound Items in .NET使用 .NET 中的数据绑定项从集合的 id 设置组合框值
【发布时间】:2021-01-22 18:59:48
【问题描述】:

我有一个组合框cbAnimal,它从仅显示动物名称的数据源绑定到这样的表。

+-----------+-------+
| id_animal |  name |
+-----------+-------+
|      3    | Cat   |
|      4    | Dog   |
|      6    | Cow   |
|      8    | Horse |
+-----------+-------+

cbAnimal 完美地显示了名称列表,我可以通过使用 ValueMember 属性选择其名称来检索 id_animal

问题是以后我还需要通过id_animal设置cbAnimal的值

例如我将传递 id 6 并且在 Combobox 上它必须显示“Cow”并且仍然允许修改。

我尝试使用:

cbAnimal.SelectedIndex= myAnimal.id_animal;

但它不起作用。

是否可以使用组合框的属性来做到这一点?

编辑:我应该澄清我正在尝试做的事情: 加载 winforms 时,如果传递的 Id_animal 当然是 6,我需要将其显示为“Cow”而不是 Cat(这是第一个元素)的默认值。

【问题讨论】:

  • 使用SelectedValue 属性而不是SelectedIndex
  • SelectedIndex 将为列表中的每个项目返回/获取索引值 (0-3)。 SelectedValue 将返回/获取与所选项目的id_animal 对应的值
  • @JayV 当我再次打开表单时,它仍然显示下拉列表的第一个元素(“Cat”)而不是“Cow”。
  • 如果您关闭并重新打开表单,则会重置数据源,因此它会转到第一项。如果要将值传递给 Form,要设置 ComboBox 选择,请在 Form.Load 或 Form.Shown 中进行,而不是在 Form 构造函数中进行。
  • 您将SelectedValue 设置为与ValueMember 定义的字段中的值匹配,从而导致选择移动当前记录。您在设计器中设置的内容在设计器中很有用,可用于评估选择更改的结果。请注意,我从未使用过数据设计器,也永远不会:生成了太多根本不需要的样板代码。 -- 如果要在 ComboBox 中设置默认值,请在 Form.Load 事件处理程序中设置SelectedValue

标签: c# .net winforms combobox


【解决方案1】:

在没有清单的情况下这样做

public class animal
{
    public int id {get; set;}
    public int name {get; set;}
    public override string ToString() // <-- new addition
    {
        return name;
    }
}

// Fill combo
comboBox.Items.Add(new animal() { id = 1, name = "dog" });
comboBox.Items.Add(new animal() { id = 2, name = "cat" });
comboBox.Items.Add(new animal() { id = 3, name = "rat" });

// later you can do this to select item by ID
comboBox.SelectedIndex = 
    comboBox.Items.Cast<animal>().ToList().FindIndex(a => a.id == 2);

或者只是循环

for(int i = 0; i < comboBox1.Items.Count; i++)
{
    if (((animal)comboBox1.Items[i]).id == 2)
    {
        comboBox.SelectedIndex = i;
        break;
    }
}

【讨论】:

  • @JuaniElias 这个答案展示了如何在没有列表的情况下做到这一点
【解决方案2】:

这样做

public class animal
{
    public int id {get; set;}
    public int name {get; set;}
}

// Fill
var animalList = new List<animal>(); 
// and bind
comboBox.ValueMember = "id";
comboBox.DisplayMemeber = "name";
comboBox.DataSource = animalList;

// later you can do this to select item
comboBox.SelectedIndex = animalList.FindIndex(a => a.id == 2);

即使你不继续引用animalList,你也可以这样做

comboBox.SelectedIndex = ((List<animal>)comboBox.DataSource).FindIndex(a => a.id == 2);

【讨论】:

  • 这很好,但是没有使用列表还有其他方法。我仍然不知道这个属性是如何工作的。
猜你喜欢
  • 2012-08-10
  • 2020-04-11
  • 2012-09-27
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-07
相关资源
最近更新 更多