Add students name,surname and age from list to Lis

2019-03-04 01:06发布

问题:

I have 3 textboxes where I can enter Name,Surname and Age. After i press button1, it makes a new student with these attributes.

How can I add student with all 3 attributes to ListBox? Look like this:

/#/ -- Name -- Surname -- Age
1 -- John -- Smith -- 21
2 -- Tony -- Hawk -- 22

My code at the moment:

public class Students
{
     public string Name;
     public string Surname;
     public int Age;
}
public partial class Form1 : Form
{
     List<Students> group = new List<Students>();
     public Form1()
     {
         InitializeComponent();
     }

     private void label1_Click(object sender, EventArgs e)
     {
         Students student = new Students();
         student.Name = textBox1.Text;
         student.Surname = textBox2.Text;
         student.Age = Convert.ToInt32(textBox3.Text);
         group.Add(student);
     }
}

回答1:

Try this:

listBox1.DataSource = group;
listBox1.DisplayMember = "Name"; //Set the DisplayMember property to avoid call ToString()

Or this:

foreach (var item in group)
{
    listBox1.Items.Add(item);
}
listBox1.DisplayMember = "Name";

Also you shoud change the fields in your class to properties like this:

public class Students
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
    public override string ToString()
    {
        return string.Format("{0} -- {1} -- {2}", Name, Surname, Age);
    }
}

Edit: I think you want this (By pressing button it adds to the ListBox and you don't need the group list anymore. Just don't forget to override the ToString in the class):

private void button1_Click(object sender, EventArgs e)
{
    Students student = new Students();
    student.Name = textBox4.Text;
    student.Surname = textBox5.Text;
    student.Age = Convert.ToInt32(textBox6.Text);
    listBox1.Items.Add(student);         
}


回答2:

If applicable, you should also have an ID (unless your specification says otherwise.) to contain the 1, 2, etc. For actually displaying the information, you can override the ToString() method to display it in the list box how you want.

public class Student
{
     public string Name { get; set; }
     public string Surname { get; set; }
     public int Age { get; set; }
     public int ID { get; set; }

     public override string ToString()
     {
          return string.Format("{0} -- {1} -- {2} -- {3}", ID, Name, Surname, Age);
     }
}

and setting the DataSource on your ListBox to 'group'.