winforms C# Win窗体,获取在格式文本框中显示的图书列表

gajydyqb  于 2022-11-16  发布在  C#
关注(0)|答案(2)|浏览(139)

我希望在格式文本框中显示图书作者和书名。下面是我的代码示例:

// Opretter info på bog
        book.Author = "Hej Preben";
        book.Title = "Hvem sagde hej?";

        // tilføjer bogen til metoden
        library.AddBook(book);
        richTextBoxBooks.Text = library.GetAllBooks().ToString();

GetallBooks返回标题和作者(以及ID),但当我查看Windows窗体时,文本框显示如下:

我的列表正在工作,我只是想知道我如何才能得到正确的信息显示,而不是这个。
我觉得卡住了,所以没有尝试过很多东西

vcudknz3

vcudknz31#

在列表中使用foreach循环:

string books = "";
    foreach(var item in someList)//replace someList with name of your list
      { //as long as [0] is not id you will have [0], [1], [2] to choose from

        books += item[0].ToString() + System.Environment.NewLine + item[1].ToString();
   
      }

richTextBoxBooks.Text = books;

我也会让你的文本框变成只读的,并且多行的. someList可以被library.getAllBooks()代替,只要它返回一个列表。

vhmi4jdf

vhmi4jdf2#

试试这个

图书和图书馆课程

namespace WinFormsApp1
{
    internal class Book
    {
        public string Author { get; private set; }
        public string Title { get; private set; }
        public Book(string author, string title)
        {
            Author = author;
            Title = title;
        }
    }

    internal class Library
    {
        private List<Book> _books { get; set; } = new List<Book>();
        public void AddBook(Book book)
        {
            _books.Add(book);
        }
        public List<Book> GetAllBooks()
        {
            return _books;
        }
    }
}

按钮单击事件

private void button1_Click(object sender, EventArgs e)
{
    var library = new Library();
    library.AddBook(new Book("Author One", "Title One"));
    library.AddBook(new Book("Author Two", "Title Two"));
    library.AddBook(new Book("Author Three", "Title Three"));

    foreach (Book book in library.GetAllBooks())
    {
        richTextBox1.Text = $"{richTextBox1.Text}{book.Author} - {book.Title}{Environment.NewLine}";
    }
}

结果

相关问题