Expander控件-读取文本文件在c# (WindowsForms)



我正试图将第二个。txt文件(book2)添加到文本扩展器控件中,不幸的是没有成功。

public Form1()
{
InitializeComponent();
CreateAccordion();
}
private void CreateAccordion(string book1)
{
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, book1, 140);
accordion.Add(expander1);
Expander expander2 = new Expander();
expander2.BorderStyle = BorderStyle.FixedSingle;
ExpanderHelper.CreateLabelHeader(expander2, "Book2", SystemColors.ActiveBorder);
CreateContentLabel(expander2, "book2", 120);
accordion.Add(expander2);
this.Controls.Add(accordion);
}

下面的代码只读取一个text .file。有人能帮帮我吗?

private void CreateAccordion()
{
ReadTxtFiles();
}
private void ReadTxtFiles()
{
string path = @"C:....READBOOKS";
string[] files = new string[] { "book1.txt", "book2.txt" };
foreach (string file in files)
{
string fullPath = Path.Combine(path, file);
string booktxt = File.ReadAllText(fullPath);
string book1 = booktxt;
CreateAccordion(book1);
}
}

我正试图将第二个。txt文件(book2)添加到文本扩展器控制中,不幸的是没有成功。

这背后的主要原因是因为您只传递第一本书的字符串,您需要传递所有的文本。

private void ReadTxtFiles()
{
string path = @"C:....READBOOKS";
string[] files = new string[] { "book1.txt", "book2.txt" };
List<string> books = new List<string>();
foreach (string file in files)
{
string fullPath = Path.Combine(path, file);
string booktxt = File.ReadAllText(fullPath);
books.Add(booktxt);                                        
}
CreateAccordion(books);
}

修改CreateAccordion的签名:

private void CreateAccordion(List<string) books)
{
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, books[0], 140);
accordion.Add(expander1);
Expander expander2 = new Expander();
expander2.BorderStyle = BorderStyle.FixedSingle;
ExpanderHelper.CreateLabelHeader(expander2, "Book2", SystemColors.ActiveBorder);
CreateContentLabel(expander2, books[1], 120);
accordion.Add(expander2);
this.Controls.Add(accordion);
}

请注意,我在这里访问索引,你可能想要检查索引是否存在之前尝试访问它。还有比这更多的方法,但应该能让你更好地理解如何完成这个任务。

最新更新