简体   繁体   中英

Listbox display from a form into a list C#

i am having a problem with a listbox, i have to add from a form into a list, and after that into a listbox, i already tried:

list <string> myList = new list<string>
Add("Blabla");
listbox1.DataSources=myList;

But that is not what i seek, i wish to add from a list of type List <student> and it doesen't work. Thank you

use data bind

listbox1.DataSource = myList;
listbox1.DataBind();

Try this:

List<string> myList = new List<string>();
List<Student> studentList = new List<Student>();
int i = 0;

foreach (var student in studentList)
{
   myList.Insert(i, student.Name);
   i++;
}

I'm guessing you know how to add the list of Students, but you're not seeing what you expect in the ListBox . You're probably just seeing the name of the class repeatedly.

Assuming this is the Student class:

public class Student
{
    public string Name { get; set; }
    public int Id { get; set; }
}

You have to tell the ListBox which field should be displayed:

var studentList = new List<Student>();
// add some students to list

listbox1.DataSource = studentList;

listbox1.DisplayMember = "Name";   // now the user will see the name
listbox1.ValueMember = "Id";

First the declaration is wrong

list <string> myList = new list<string>(); 
myList.Add("Blabla");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM