Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

.net - How to create a Winforms Combobox with Label and Value?

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".

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?

  • Toronto / 2324
  • Montreal / 64547
  • Vancouver / 1213
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I can think of a few ways:

  • 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

For the last:

var data = cities.Select(city => new {
     Id = city.Id, Text = city.Name + " / " + city.Id }).ToList();
cbo.ValueMember = "Id";
cbo.DisplayMember = "Text";
cbo.DataSource = data;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...