将列表中的学生姓名、姓氏和年龄添加到 ListBox

Add students name,surname and age from list to ListBox(将列表中的学生姓名、姓氏和年龄添加到 ListBox)
本文介绍了将列表中的学生姓名、姓氏和年龄添加到 ListBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 3 个 文本框,我可以在其中输入 NameSurnameAge.在我按下button1后,它会生成一个具有这些属性的新学生.

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

如何将具有所有 3 个属性的学生添加到 ListBox?看起来像这样:

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

/#/-- 姓名 -- 姓 -- 年龄
1 -- 约翰 -- 史密斯 -- 21
2 --托尼 -- 霍克 -- 22

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

我现在的代码:

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);
     }
}

推荐答案

试试这个:

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

或者这个:

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);
    }
}

我想你想要这个(通过按下按钮它添加到 ListBox 并且你不再需要 group 列表. 只是不要忘记覆盖类中的ToString):

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);         
}

这篇关于将列表中的学生姓名、姓氏和年龄添加到 ListBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)