Reputation: 165
I have created a List called employees
and I want to input all of the information from that List
into a list box on the form.
I cannot believe I have forgotten this I have had a look around and I cannot find any concise information, I have a study book, but they use a TextBox
instead of a ListBox
and they only work with arrays and simple data types.
List<Employee> employees = new List<Employee>();
This is the list, it contains employees
Employee employee1 = new Employee(1111, "Name", "Skill Set");
I have created an instance of List
Then I add it to the list box on the form
lstFree.Items.Add(employees);
Yet it only appears as 'collection'
What am I doing wrong?
Upvotes: 1
Views: 5147
Reputation: 66499
The Add
method expects a single instance of your class. When you pass a collection to it, it calls ToString()
and you end up seeing the full class name of the collection. Not what you want.
Instead, you could use a loop:
foreach (var emp in employees)
lstFree.Items.Add(emp);
Or just assign it to DataSource
:
listBox1.DataSource = employees;
You'll also want to tell it which property to display to the user (and optionally, which property to use as the underlying value):
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "EmpId"; // guessing what your class properties might be called
Upvotes: 4
Reputation: 6103
Consider using AddRange.
object[] arr = Enumerable.Range(1, 10000).Select(i=>(object)i).ToArray();
Compare time of this
// 1,29s
foreach (int i in arr)
{
listBox1.Items.Add(i);
}
to this
// 0,12s
listBox1.Items.AddRange(arr);
Upvotes: 2
Reputation: 1011
List<Employee> employees = new List<Employee>();
Employee employee1 = new Employee(1111, "Name", "Skill Set");
Employee employee2 = new Employee(2222, "Name", "Skill Set");
employees.Add(employee1);
employees.Add(employee2);
foreach(var empl in employees)
{
listBox1.Items.Add(empl.ToString());
}
In Employee class:
public override string ToString()
{
return ""; // return what you need
}
Upvotes: 3