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

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

Mary-Kate Olsen
Release: 2025-01-12 06:33:46
Original
797 people have browsed it

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

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>
Copy after login

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:

  1. Instantiate a ComboboxItem object.
  2. Set the Text property to the desired display text.
  3. Set the Value property to the associated value.
  4. Add the ComboboxItem object to the ComboBox's Items collection.

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>
Copy after login

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!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template