如何创建一个WinForms组合框与标签和价值? [英] How to create a Winforms Combobox with Label and Value?
问题描述
我主要是ASP.NET开发人员,但我工作的一个WinForms应用程序,并注意到了ASP.NET组合框(HTML选择),而的WinForms之间的较大差异。我发现(也许不正确的话)的WinForm中的组合框只有一个标签,而ASP.NET允许你指定一个标签和价值。
I am mostly an ASP.NET developer but I am working on a WinForms app and noticed a large difference between the ASP.NET combobox (html select) and that of WinForms. I found (maybe incorrectly so) that WinForm's combobox only has a "label" whereas ASP.NET allows you to specify a "label" and a "value".
我期待使用的WinForms组合框(或其他可比较的控制)与一个标签和一个值(Foobar的/ 42329)。这可能吗?我试图寻找答案,但没有拿出太多。如果没有办法实现这个目标,一个人如何继续前进,设计一个WinForm组合框,将重新present说与他们相关联的数据库ID城市?
I am looking to use a WinForms combobox (or another comparable control) with a label and a value (Foobar / 42329). Is this possible? I have attempted to search for the answer but haven't come up with much. If there is no way to accomplish that, how does one go ahead and design a WinForm combobox that would represent say Cities with their associated database id?
- 在多伦多/ 2324
- 在蒙特利尔/ 64547
- 在温哥华/ 1213
推荐答案
我能想到的几种方法:
- 覆盖
的ToString()
A城
类返回名称+的/ +标识;
- 同上,但与
类型转换器
- 添加
DisplayText
属性返回相同的,并使用的DisplayMember
- 的数据建立一个垫片类
- override the
ToString()
of aCity
class toreturn Name + " / " + Id;
- ditto, but with a
TypeConverter
- add a
DisplayText
property that return the same, and useDisplayMember
- build a shim class for the data
在过去的:
var data = cities.Select(city => new {
Id = city.Id, Text = city.Name + " / " + city.Id }).ToList();
cbo.ValueMember = "Id";
cbo.DisplayMember = "Text";
cbo.DataSource = data;
这篇关于如何创建一个WinForms组合框与标签和价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!