The problem is this: I linked ListBoxto a list of elements of some custom class ( List<Person> persons = new List<Person>()) using a property DataSource. Of course, ValueMemberand DisplayMembertwo appointed by the properties of this class. When I first upload the data, everything looks fine. However, when I click on an element (i.e. the 7th position, counting from 1), and then rebuild the list AND the number of elements is less than MANY, as a result I do not see the corresponding texts in the list. Instead, each element is displayed as a class name preceded by a namespace.
In other words, instead of a list:
- John doe
- Jane doe
- Someone else
I see it:
- MyNamespace.Person
- MyNamespace.Person
- MyNamespace.Person
, SelectedIndex. ( ), .
ValueMember DisplayMember, null DataSource , -1 SelectedIndex , .
[]
. :
1. :
public class Person
{
private int id;
private string name;
public Person(int m_id, string m_name)
{
id = m_id;
name = m_name;
}
public int Id
{
get
{
return id;
}
}
public string Name
{
get
{
return name;
}
}
}`
2. :
List<Person> persons = new List<Person>();
3. , 1, :
listBox1.DataSource = null;
persons.Add(new Person(1, "John Doe"));
persons.Add(new Person(2, "Jane Doe"));
persons.Add(new Person(3, "Somebody Else"));
listBox1.ValueMember = "Id";
listBox1.DisplayMember = "Name";
listBox1.DataSource = persons;
4. , buton2, :
listBox1.DataSource = null;
persons.Add(new Person(1, "Person One"));
persons.Add(new Person(2, "Person Two"));
listBox1.ValueMember = "Id";
listBox1.DisplayMember = "Name";
listBox1.DataSource = persons;
1, , . ( "Somebode Else" ), clisk button2, 2 : "MyNamespace.Person".
[ 2 - ]
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace MyNamespace
{
public partial class Form1 : Form
{
private List<Person> persons = new List<Person>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
persons.Clear();
persons.Add(new Person(1, "John Doe"));
persons.Add(new Person(2, "Jane Doe"));
persons.Add(new Person(1, "Somebody Else"));
listBox1.DataSource = null;
listBox1.ValueMember = "Id";
listBox1.DisplayMember = "Name";
listBox1.DataSource = persons;
}
private void button2_Click(object sender, EventArgs e)
{
persons.Clear();
persons.Add(new Person(1, "Person One"));
persons.Add(new Person(2, "Person Two"));
listBox1.DataSource = null;
listBox1.ValueMember = "Id";
listBox1.DisplayMember = "Name";
listBox1.DataSource = persons;
}
}
class Person
{
private int id;
private string name;
public Person(int m_id, string m_name)
{
id = m_id;
name = m_name;
}
public int Id
{
get
{
return id;
}
}
public string Name
{
get
{
return name;
}
}
public string ToString()
{
return id + ". " + name;
}
}
}
:
"John Doe" "Jane Doe" , . , "", . , .