Home >Backend Development >C++ >How to Customize ComboBox Items in C# WinForms Without Data Binding?
Customize ComboBox items in C# WinForms without data binding
In C# WinForms applications, developers often need to add text and values to ComboBox items without using the data binding mechanism. This is different from the commonly suggested solutions that rely on binding to external data sources.
Implement custom classes
In order to achieve the required functionality, developers can create a custom class and override the ToString() method to define the display text of the ComboBox item. Here is an example of such a 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>
How to use
After defining the custom class, developers can use it to create and add items to the ComboBox as follows:
<code class="language-csharp">private void Test() { ComboboxItem item = new ComboboxItem(); item.Text = "项目文本1"; item.Value = 12; comboBox1.Items.Add(item); comboBox1.SelectedIndex = 0; MessageBox.Show((comboBox1.SelectedItem as ComboboxItem).Value.ToString()); }</code>
In this case, the ComboBox contains an item that displays the text specified by the Text property and holds any value assigned to the Value property. There is an option to directly retrieve and access the value of the selected item.
The above is the detailed content of How to Customize ComboBox Items in C# WinForms Without Data Binding?. For more information, please follow other related articles on the PHP Chinese website!