Home > database >  C# Win form. Getting a list of books displayed in a rich text box
C# Win form. Getting a list of books displayed in a rich text box

Time:10-28

I want to get the book author and the book title displayed in my rich text box. Here is a sample of my code:

        // 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();

The GetallBooks is returning title and author (and a id), but when i look at my windows form, my textbox is displaying this: Rich text box

My list is working, I just want to know how I can get the correct info displayed, insted of this.

Im feeling stuck, so have not tried many things

CodePudding user response:

Use a foreach loop on your list:

    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;

I woud also make yor textbox read only, and multiline. someList could be replaced by library.GetAllBooks() as long as it returns a list.

CodePudding user response:

Try this

Book and Library classes

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;
        }
    }
}

Button click event

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}";
    }
}

Result

enter image description here

  • Related