lorenzoid
lorenzoid

Reputation: 1832

C# Passing objects between forms

So I have two forms. LibraryBookDialog.cs and MainForm.cs. I'm trying to pass an object from LibraryBookDialog.cs to Mainform.cs. Problem is, I get this error when I try to do so...

object reference not set to an instance of the object

Here are my two forms...

LibraryBookDialog.cs:

private LibraryBook book;

public LibraryBook Book
{
    get { return book;}
    set { book = value;} 
}

private void buttonOk_Click(object sender, EventArgs e)
    {
        if (validateData())
        {
            try
            {
                Book.Title = textBoxTitle.Text; 
                Book.Author = textBoxAuthor.Text;
                Book.CopyrightYear = Convert.ToInt32(textBoxCopyrightYear.Text);
                this.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "There was an error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

and MainForm.cs

private void buttonNew_Click(object sender, EventArgs e)
    {
        LibraryBookDialogue dlg = new LibraryBookDialogue();
        dlg.ShowDialog();

        if (dlg.DialogResult == DialogResult.OK)
        {
            listBoxLibraryBooks.Items.Add(dlg.Book);
        }
        dlg.Dispose();
    }

Why is this happening?

Upvotes: 0

Views: 2175

Answers (3)

John
John

Reputation: 6553

private LibraryBook book = new LibraryBook();

or

private void buttonOk_Click(object sender, EventArgs e)
{
    if (validateData())
    {
        try
        {
            // Create book instance and assign properties
            Book = new LibraryBook()
            {
                Title = textBoxTitle.Text,
                Author = textBoxAuthor.Text,
                CopyrightYear = Convert.ToInt32(textBoxCopyrightYear.Text)
            };
            this.DialogResult = DialogResult.OK;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "There was an error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}

Upvotes: 2

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28738

You need to initialize the Book property. It's never set to a value, so it will be null when you go to use it.

You could do something like this.

public LibraryBook Book
{
    get 
    { 
        if (book == null)
        {
            book = new LibraryBook();
        }
        return book;
    }
    set { book = value;} 
}

Upvotes: 1

SLaks
SLaks

Reputation: 888117

It looks like you never put a LibraryBook instance into the Book property.

Upvotes: 2

Related Questions