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

C# Windows Forms文件处理时pets列表无法显示到ListBox及保存到文本文件求助

问题排查与解决方案

1. ListBox无法显示pets列表信息

  • 核心原因:直接将Pet类对象添加到ListBox的Items集合时,默认会调用对象的默认ToString()方法,输出类的完整命名空间路径,不会展示属性内容。
  • 解决方法:
    方案一:重写Pet类的ToString()方法,自定义展示内容,示例如下:
    public class Pet
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public double Price { get; set; }
    
        public Pet(string name, int age, double price)
        {
            Name = name;
            Age = age;
            Price = price;
        }
    
        public override string ToString()
        {
            return $"姓名:{Name},年龄:{Age},价格:{Price:F2}";
        }
    }
    
    方案二:给ListBox指定展示的属性名,在窗体初始化逻辑中添加代码listBox1.DisplayMember = "Name",即可直接展示Pet对象的Name属性,如需展示多字段内容推荐使用方案一。

2. 无法将数据保存到文本文件

  • 核心原因:创建StreamWriter对象后,仅设置了ListBox的DataSource属性,没有执行任何写入文件的操作,文件自然不会有内容。另外原代码中IO操作未做资源自动释放,容易出现资源泄漏问题。
  • 修正后的业务代码示例:
private void btnRun_Click(object sender, EventArgs e)
{
    List<Pet> pets = new List<Pet>();
    pets.Add(new Pet("Rex", 4, 500.00));
    pets.Add(new Pet("Mittens", 2, 125.50));
    pets.Add(new Pet("Clifford", 7, 30.00));
    writePets(pets);
}

private void writePets(List<Pet> pets)
{
    listBox1.Items.Clear();
    foreach(var pet in pets)
    {
        listBox1.Items.Add(pet);
    }

    // 如不需要读取现有文件内容追加到ListBox,可删除以下打开文件的逻辑
    /*
    OpenFileDialog ofd = new OpenFileDialog();
    if(ofd.ShowDialog() == DialogResult.OK)
    {
        using (StreamReader sr = new StreamReader(ofd.FileName))
        {
            string line = sr.ReadLine();
            while(line != null)
            {
                listBox1.Items.Add(line);
                line = sr.ReadLine();
            }
        }
    }
    */
    
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Filter = "文本文件(*.txt)|*.txt";
    if(sfd.ShowDialog() == DialogResult.OK)
    {
        // using语句会自动释放StreamWriter资源,无需手动调用Close
        using (StreamWriter sw = new StreamWriter(sfd.FileName))
        {
            // 遍历ListBox所有项逐行写入
            foreach (var item in listBox1.Items)
            {
                sw.WriteLine(item.ToString());
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者Priyam Patel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:45:04