Add text and value to ComboBox programmatically
In C# WinApp, you can add text and values to a ComboBox's items without using a binding source.
To do this, you can create your own class type and override the ToString() method to return the desired text. For example, 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 allows you to specify the display text and associated value for each item in the ComboBox.
To use this class, follow these steps:
For example:
<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>
By following these steps, you can dynamically add items with text and values to a ComboBox without using a binding source.
The above is the detailed content of How to Programmatically Add Text and Value to a C# WinForms ComboBox without Binding?. For more information, please follow other related articles on the PHP Chinese website!