Home >Backend Development >C++ >How to Add Custom Text and Value Pairs to a WinForms ComboBox in C#?
Add custom text and values to ComboBox items
In a C# WinForms application, you may need to populate your ComboBox with items that contain human-readable text and additional associated values. While many solutions rely on data binding, in some cases the binding source may not be available.
In this case, you can leverage the capabilities of a custom class to achieve the desired functionality. Consider the following class:
<code class="language-csharp">public class ComboboxItem { public string Text { get; set; } public object Value { get; set; } public override string ToString() { return Text; } }</code>
This class defines two properties: Text for displaying the value and Value for saving the associated value. By overriding the ToString() method, we ensure that the Text property is returned when converting the ComboboxItem to a string.
To use this class, just create an instance and add it to your ComboBox like this:
<code class="language-csharp">private void Test() { ComboboxItem item = new ComboboxItem(); item.Text = "Item text1"; item.Value = 12; comboBox1.Items.Add(item); comboBox1.SelectedIndex = 0; MessageBox.Show((comboBox1.SelectedItem as ComboboxItem).Value.ToString()); }</code>
In this example, we create a ComboboxItem instance, assign its Text and Value properties, and add it to the ComboBox’s Items collection. By setting SelectedIndex to 0, we select the newly added item. When the item is selected, we retrieve and display its Value property.
The above is the detailed content of How to Add Custom Text and Value Pairs to a WinForms ComboBox in C#?. For more information, please follow other related articles on the PHP Chinese website!