Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why overriden ToString() do not return what I want when item added to ComboBox?

public partial class TestConrol : UserControl
{
    public TestConrol()
    {
        InitializeComponent();
    }

    public override string ToString()
    {
        return "asd";
    }
}

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        TestConrol tc1 = new TestConrol();
        comboBox1.Items.Add(tc1);

        TestConrol tc2 = new TestConrol();
        comboBox1.Items.Add(tc2);
    }
}

When form loaded, I see combobox has two items with empty names, instead of "asd" :/
But this work if I override ToString() in common class, not derived from anything:

public class TestClass
{
    public override string ToString()
    {
        return "bla bla bla";
    }
}

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        TestClass tcl = new TestClass();
        comboBox1.Items.Add(tcl);
    }
}

After that I see in combobox "bla bla bla"

like image 972
Kosmo零 Avatar asked Jan 13 '23 17:01

Kosmo零


1 Answers

Create a property in you control and map the DisplayMember of the combobox to that property, it should work.

like image 59
MeTitus Avatar answered Feb 05 '23 17:02

MeTitus