C#: ComboBox: Adding Text And Value To An Item (no Binding Source)

In C#, you can add text and value to an item in a ComboBox by using the ComboBoxItem class. Here’s an example:

comboBox.Items.Add(new ComboBoxItem { Content = "Item 1", Tag = 1 });
comboBox.Items.Add(new ComboBoxItem { Content = "Item 2", Tag = 2 });
comboBox.Items.Add(new ComboBoxItem { Content = "Item 3", Tag = 3 });

// Get the selected item's value
ComboBoxItem selectedItem = (ComboBoxItem)comboBox.SelectedItem;
int selectedValue = (int)selectedItem.Tag;

In this example, we are creating ComboBoxItem objects and adding them directly to the Items collection of the ComboBox. You can set the Content property to specify the display text of the item, and the Tag property to specify the associated value.

To retrieve the selected item’s value, you need to cast the SelectedItem property of the ComboBox to a ComboBoxItem, and then access the Tag property to get the value.

Note: If you are using data binding, it’s recommended to use a BindingSource and bind it to the Items property of the ComboBox instead of manually adding the items.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!