Home > Backend Development > C++ > How to Add Both Text and Value to ComboBox Items in C# Without Data Binding?

How to Add Both Text and Value to ComboBox Items in C# Without Data Binding?

Linda Hamilton
Release: 2025-01-12 08:24:41
Original
556 people have browsed it

How to Add Both Text and Value to ComboBox Items in C# Without Data Binding?

Add text and value to combo box item in C# WinForms app

Many answers about adding text and values ​​to combo box items in C# WinForms applications involve data binding. However, if there is no ready-made binding source, another approach is needed.

To achieve this, create a custom class and override the ToString() method to return the desired text. Here's a simple example:

public class ComboboxItem
{
    public string Text { get; set; }
    public object Value { get; set; }

    public override string ToString()
    {
        return Text;
    }
}
Copy after login

How to use it:

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());
}
Copy after login

This makes it possible to add text and values ​​to combo box items without binding a source.

The above is the detailed content of How to Add Both Text and Value to ComboBox Items in C# Without Data Binding?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template