You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Visual Studio的WinForms中用自定义类填充ListBox并实现联动

问题解决方法

你的代码存在两个核心问题导致ListBox无内容:

  1. 未将创建的Person实例加入people列表:foreach (Person b in people)循环时,people是空的,循环根本不会执行,自然没有内容添加到ListBox。
  2. 多余的ToString()调用:lstRoster.Items.Add(p.Name).ToString()完全无效,Add方法已经把Name添加到ListBox,此处的ToString()是对返回的索引值调用,不会影响ListBox内容。

修正后的完整实现

1. 读取CSV并填充ListBox的方法

把people列表存为类的私有字段,方便后续选中事件使用;同时用using语句自动释放文件流(比手动Close更安全):

private List<Person> _allPeople; // 存储所有Person实例的类字段

public void Get_Roster()
{
    // 清空ListBox原有内容
    lstRoster.Items.Clear();
    _allPeople = new List<Person>();

    using (System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Users\Austin316\Desktop\yourFile.txt"))
    {
        string line;
        while ((line = file.ReadLine()) != null)
        {
            // 跳过空行
            if (string.IsNullOrWhiteSpace(line)) continue;
            
            string[] words = line.Split(',');
            // 防止CSV行字段数量不足导致索引越界
            if (words.Length < 12) continue;
            
            Person p = new Person(words[0], words[1], words[2], words[3], words[4], words[5], words[6], words[7], words[8], words[9], words[10], words[11]);
            _allPeople.Add(p);
            // 直接添加Person对象到ListBox,设置DisplayMember显示Name属性
            lstRoster.Items.Add(p);
        }
    }
    // 指定ListBox显示Person的Name属性
    lstRoster.DisplayMember = "Name";
}

2. 处理ListBox选中事件更新标签

在Form的构造函数或Load事件中绑定选中事件,然后实现事件逻辑:

public YourFormName()
{
    InitializeComponent();
    // 绑定选中事件
    lstRoster.SelectedIndexChanged += lstRoster_SelectedIndexChanged;
}

private void lstRoster_SelectedIndexChanged(object sender, EventArgs e)
{
    // 判断选中项是否为Person实例
    if (lstRoster.SelectedItem is Person selectedPerson)
    {
        // 更新对应标签内容
        lblName.Text = selectedPerson.Name;
        lblGender.Text = selectedPerson.Gender;
        lblWeight.Text = selectedPerson.Weight.ToString();
        // 其他属性标签同理设置
    }
}

补充说明

  • 直接添加Person对象到ListBox比添加Name字符串更灵活,后续选中时无需通过Name查找实例,直接强转即可。
  • 加入了空行和字段长度判断,避免CSV格式异常导致程序崩溃。

内容的提问来源于stack exchange,提问作者Braden Putt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 14:55:41