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
Linda HamiltonOriginal
2025-01-12 08:24:41526browse

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:

<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 it:

<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>

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:
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