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

C# WindowsForms下Expander控件加载多个txt文件的问题咨询

问题排查与修复方案

核心问题点

  • 循环读取文件时每读1个文件就创建1个新的Accordion控件,多次创建的控件堆叠在窗体上,后创建的会覆盖先创建的
  • CreateAccordion(string book1)方法中第二个Expander的内容为硬编码的固定字符串"book2",没有绑定实际读取到的book2.txt内容
  • 逻辑顺序错误:应该先读取完所有文件内容,再一次性创建Accordion并绑定两个文件的内容,而非读一个文件创建一次控件

修复后代码

1. 文件读取逻辑

private void CreateAccordion()
{
    List<string> bookContents = ReadTxtFiles();
    CreateAccordion(bookContents[0], bookContents[1]);
}

private List<string> ReadTxtFiles()
{
    string path = @"C:\..\..\READBOOKS";
    string[] files = new string[] { "book1.txt", "book2.txt" };
    List<string> contents = new List<string>();

    foreach (string file in files)
    {
        string fullPath = Path.Combine(path, file);
        contents.Add(File.ReadAllText(fullPath));
    }
    return contents;
}

2. 控件创建逻辑

private void CreateAccordion(string book1Content, string book2Content)
{
    Accordion accordion = new Accordion();
    accordion.Size = new Size(400, 350);
    accordion.Left = 10;

    Expander expander1 = new Expander();
    expander1.BorderStyle = BorderStyle.FixedSingle;
    ExpanderHelper.CreateLabelHeader(expander1, "Book1", SystemColors.ActiveBorder);
    CreateContentLabel(expander1, book1Content, 140);
    accordion.Add(expander1);

    Expander expander2 = new Expander();
    expander2.BorderStyle = BorderStyle.FixedSingle;
    ExpanderHelper.CreateLabelHeader(expander2, "Book2", SystemColors.ActiveBorder);
    CreateContentLabel(expander2, book2Content, 120);
    accordion.Add(expander2);
    this.Controls.Add(accordion);
}

修改说明

  • 仅在读取完所有文件内容后创建1次Accordion控件,避免重复生成覆盖的问题
  • 调整CreateAccordion方法入参,同时接收两个文件的内容,分别绑定到对应的Expander控件
  • 移除了第二个Expander内容的硬编码,替换为实际读取到的book2.txt内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:36:00