Why ComboBox doesn't throw an Exception when setting DataSource?

Viewed 788

First my code. I have a class:

class Person {
    public int Id { set; get; }
    public string Name { set; get; }
    public Person(int i, string n) {Id = i; Name = n;}
}

and a ComboBox object:

this.comboBox_Persons = new System.Windows.Forms.ComboBox();

and somewhere in my code:

List<Person> persons = new List<Person>() {
    new Person(5, "John"),
    new Person(8, "Mike")
};
comboBox_Persons.Items.Clear();
comboBox_Persons.DisplayMember = "Name";
comboBox_Persons.ValueMember = "Id";
comboBox_Persons.DataSource = persons;

and a static member and an event handler:

public static string test = "";

void comboBox_PersonsSelectedIndexChanged(object sender, EventArgs e)
{
    test = test + "1";
    string id = (string) comboBox_Persons.SelectedValue;
}

The last line is wrong (it comes from an earlier version of my code) and it should be:

int id = (int) comboBox_Persons.SelectedValue;

and it took me some time to realize that my problem is in this line.

But my question is about the wrong version of the line and exactly about the code above.

Why no exception is thrown when comboBox_Persons.DataSource is beeing filled?

When my form is ready comboBox_Persons contains two items and it should display "John" and "Mike" but it does not. The combobox displays the type name (with namespace) of the class Person twice. Moreover, the value of the static field 'test' is "11" which means that the event handler has been invoked. But the next line (with casting to string) should throw an exception, but it does not. Why? And next, when I click on the combobox and change the selected value then the event handler is called and an exception is thrown (telling that it can't cast to string).

So, why combobox does not throw any exception when setting DataSource?

And why combobox displays type names instead of defined property 'Name'?

I wonder why this control behaves this way and I didn't find any answer in .NET documentation and on the Internet.

When I change the wrong line to the correct version everything is OK.

2 Answers
Related