Home >Backend Development >C++ >How to Add Custom Text and Value to a C# WinForms ComboBox without a Binding Source?

How to Add Custom Text and Value to a C# WinForms ComboBox without a Binding Source?

Barbara Streisand
Barbara StreisandOriginal
2025-01-12 07:43:46984browse

How to Add Custom Text and Value to a C# WinForms ComboBox without a Binding Source?

Customize the ComboBox project without binding sources

When using a ComboBox in C# WinApp, the typical way to add text and values ​​to its items involves binding to a data source. However, if you don't have an existing binding source, you'll need another solution.

Solution: Custom class that overrides ToString() method

To overcome this limitation, create a custom class that contains both text and value properties. Override the ToString() method to return the desired text. Here is an example of such a class:

<code class="language-c#">public class ComboboxItem
{
    public string Text { get; set; }
    public object Value { get; set; }

    public override string ToString()
    {
        return Text;
    }
}</code>

Usage:

After defining your custom class, you can create instances and add them to the ComboBox:

<code class="language-c#">private void Test()
{
    ComboboxItem item = new ComboboxItem();
    item.Text = "项目文本1";
    item.Value = 12;

    comboBox1.Items.Add(item);
}</code>

Retrieve value:

To retrieve the underlying value of the selected item, cast it to a custom class and access the Value property:

<code class="language-c#">MessageBox.Show((comboBox1.SelectedItem as ComboboxItem).Value.ToString());</code>

This customization method allows you to populate the ComboBox with specific text that differs from its actual value, providing greater flexibility when managing projects without a dedicated data source.

The above is the detailed content of How to Add Custom Text and Value to a C# WinForms ComboBox without a Binding Source?. 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