如何创建带有标签和值的 Winforms 组合框? [英] How to create a Winforms Combobox with Label and Value?

查看:20
本文介绍了如何创建带有标签和值的 Winforms 组合框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我主要是一名 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".

我希望使用带有标签和值 (Foobar/42329) 的 WinForms 组合框(或其他类似控件).这可能吗?我试图寻找答案,但没有想出太多.如果没有办法做到这一点,那么如何设计一个 WinForm 组合框来表示具有关联数据库 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

推荐答案

我能想到几个办法:

  • 覆盖City 类的ToString()return Name + "/" + Id;
  • 同上,但带有 TypeConverter
  • 添加返回相同的 DisplayText 属性,并使用 DisplayMember
  • 为数据构建一个填充类
  • override the ToString() of a City class to return Name + " / " + Id;
  • ditto, but with a TypeConverter
  • add a DisplayText property that return the same, and use DisplayMember
  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆