The question is, there is a combo box in which the choice of the text version takes place. It is necessary to make the selected text variant correspond to a specific number and fit as a variable into a function. For example, options: tea, coffee - corresponds to the number 100, options: lemonade, juice number 200. The numbers themselves are not visible in the combo box. It occurred to me to assign some id to variants from one group and then read it using a regular expression (but how to hide this id?). Maybe there is a simpler solution?
1 answer
Combobox has a ValueMember property.
Suppose you have a List<Product> list which contains a collection of the form Name | Id You do the following:
Combobox.DataSource=list; Combobox.DisplayMember="Name"; Combobox.ValueMember="Id"; If you use VS2015, then you can do a little, more beautiful, getting rid of string literals,
Combobox.DataSource=list; Combobox.DisplayMember=nameof(Product.Name); Combobox.ValueMember=nameof(Product.Id); The result is that some name is displayed, and in SelectedValue your Id
- Thank you, got the idea. I added elements to combobox via comboBox.Items.AddRange (new object [] {}); I understand it is necessary to describe the functionality in the Product class and add a collection of type Product to the combo box, right? - cruim
- @cruim, List <> I gave for example. You can do the same thing through a Dictionary <T, T>. In any case, you need some kind of container. - iluxa1810
- I did everything according to the scheme (I used the sheet), I launch it - everything works. But when I try to enter the form designer, I get the error Failed to parse method 'InitializeComponent'. The object of the object is the following. Please look at the Task List for potential errors. - cruim
- @cruim, if your form designer has broken, then you have nakosyachil somewhere. Perhaps you climbed the InitializeComponent method and broke something there ... - iluxa1810
- as far as I understood, these lines are Combobox.DataSource = list; Combobox.DisplayMember = nameof (Product.Name); must be registered in the InitializeComponent method, right? If you comment out these changes, the designer works. - cruim
|