I am trying to save data to ArrayList() by using following code in WinForm application. The problem is when I do this my output in bookList.txtBookList.Text is Lab_8.Book and I can’t figure out why. Hope for some tips.
BookEntry.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace Lab_8
{
public partial class BookEntry : Form
{
private ArrayList books = new ArrayList();
private BookList bookList = new BookList();
public BookEntry()
{
InitializeComponent();
}
private void btnEnter_Click(object sender, EventArgs e)
{
books.Add(new Book(txtTitle.Text, txtFirstName.Text,
txtLastName.Text, txtPublisher.Text,
float.Parse(txtPrice.Text)));
}
private void btnShowBooks_Click(object sender, EventArgs e)
{
foreach (object list in books)
{
bookList.txtBookList.Text += list.ToString() + "\n";
}
bookList.ShowDialog();
}
}
}
Book.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lab_8
{
class Book : Publication
{
private string authorFirstName, authorLastName;
public Book()
{ }
public Book(string title, string firstName, string lastName, string publisherName, float price)
: base(title, publisherName, price)
{
this.authorFirstName = firstName;
this.authorLastName = lastName;
}
public string getAuthorName()
{
return authorFirstName + " " + authorLastName;
}
public string AuthorFirstName
{
get
{
return authorFirstName;
}
set
{
authorFirstName = value;
}
}
public string AuthorLastName
{
get
{
return authorLastName;
}
set
{
authorLastName = value;
}
}
}
}
Regards. HelpNeeder
The problem here is the
Bookdoesn’t overrideToString, which means this loop:Will just print out the name of the class (with the namespace), or
Lab_8.Book.In order to correct this, you could override
ToString()inBook:That being said, I would highly recommend converting the
ArrayListto useList<Book>instead. This will allow you to refer to the books as a book directly, ie:The only change required for this would be to change:
To:
And then also change the list as above…