代码之家  ›  专栏  ›  技术社区  ›  netmajor

使用类似组合框的控件连接自定义列表

  •  1
  • netmajor  · 技术社区  · 15 年前

    我有表自定义id(如1.10、1.20)和名称(值可以重复的字符串)。我的问题是把它设置成winForms控件,比如combobox。但我想,该用户在字段中只会看到名称和id将不可见,但潜意识中应连接到名称控制,当用户选择组合框中的项目,我可以得到这个id。

    你知道这有可能吗?

    4 回复  |  直到 15 年前
        1
  •  2
  •   davehauser    15 年前

    按如下方式设置组合框:

    // item type to display in the combobox
    public class Item
    {
        public int Id { get; set; }
        public string Text { get; set; }
    }
    
    // build new list of Items
    var data = List<Item>
    {
        new Item{Id = 1, Text = "Item 1"},
        new Item{Id = 2, Text = "Item 2"},
        new Item{Id = 3, Text = "Item 3"}
    };
    
    // set databind
    comboBox1.DataSource = data;
    comboBox1.ValueMember = "Id";  // the value of a list item should correspond to the items Id property
    comboBox1.DisplayMember = "Text";  // the displayed text of list item should correspond to the items Id property
    
    // get selected value
    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        var selectedValue = comboBox1.SelectedValue;        
    }
    
        2
  •  1
  •   Hari Menon    15 年前

    使用 DisplayMember 属性设置要显示和使用的内容 ValueMember

    e、 在你的情况下,设置 DataSource 坐到桌子上, 显示值 估价员

        3
  •  1
  •   Albin Sunnanbo    15 年前

    绑定到列表:

    项目:

    class MyItem
    {
        public int Id { get; set; }
        public string DisplayText { get; set; }
    }
    

    设置绑定:

    List<MyItem> items = new List<MyItem>
    {
        new MyItem(){ Id = 1, DisplayText = "one"},
        new MyItem(){ Id = 2, DisplayText = "two"},
    };
    
    comboBox1.DisplayMember = "DisplayText"; // or whatever field your you want to display
    comboBox1.DataSource = items;
    

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        var item = comboBox1.SelectedItem as MyItem;
        if (item != null)
            Console.WriteLine(item.Id);
    }
    
        4
  •  0
  •   Rob    14 年前

    摆脱ItemData的概念是微软有史以来做过的最愚蠢的事情之一。实际上是麻木了。

    下面是一个模仿这种行为的链接。 ItemData

    推荐文章