1

I'm new to C# and I just have a quick question about adding to an array list. I have an arraylist which shows some details about different books (Name, Genre, Author and Year Published). How can I make it so that a user can input all these values (name, genre, etc) into multiple textboxes and then click a button to add all the details as a new book in the list?

Below is my code so far:

namespace LibraryBooks
{
    public partial class Form1 : Form
    {
        List<Object> library = new List<Object>();
        int current = 0;

        public Form1()
        {
            InitializeComponent();
            InitializeArrayList();
            DisplayData();
        }
        public void DisplayData()
        {
            Books b = (Books)library[current];
            textBox1.Text = "" + b.readTitle();
            textBox2.Text = "" + b.readGenre();
            textBox3.Text = "" + b.readAuthor();
            textBox4.Text = "" + b.readYearPublished();
        }
        public void InitializeArrayList()
        {
            library.Add(new Books("The Hunger Games", "Adventure", "Suzanne Collins", "2008"));
            library.Add(new Books("Gone Girl", "Thriller", "Gillian Flynn", "2014"));
            library.Add(new Books("A Game of Thrones", "Fantasy", "George R.R. Martin", "1996"));
        }
        private void button5_Click(object sender, EventArgs e)
        {
            if (movies.Contains(textBox7.Text))
            {
                textBox1.Text = "";
            }
        }
    }
    public class Test92
    {
        public static void Main(string[] args)
        {
            Application.Run(new Form1());
        }
    }
}

I'm not sure how to go about it at all so any ideas would be appreciated.

1
  • 1
    Why is library a List<Object> and not a List<Books> (or rather, List<Book>)? Commented Nov 17, 2015 at 20:44

1 Answer 1

1

It's very simple. Create all the textboxes you need for each input, and then in your button_click method, write something along the lines of

library.Add(new Books(textbox1.text, textbox2.text, textbox3.text));

This functions very similarly to what your InitializeArrayList method does, but instead of passing pre-determined text to your Books constructor, it takes in text from the textboxes on your form.

Sign up to request clarification or add additional context in comments.

1 Comment

I would suggest using a masktextbox for the year variable. The books class looks like it can be book in singular. As a coding convention, plural of things is reserved for collections. I suggest renaming the class to book.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.