C#在表单之间传递对象

时间:2011-11-06 03:06:38

标签: c# winforms object

所以我有两种形式。 LibraryBookDialog.cs和MainForm.cs。我正在尝试将LibraryBookDialog.cs中的对象传递给Mainform.cs。问题是,当我尝试这样做时,我收到了这个错误......

object reference not set to an instance of the object

以下是我的两种表格......

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

和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();
    }

为什么会这样?

3 个答案:

答案 0 :(得分:2)

看起来您从未将LibraryBook实例放入Book属性。

答案 1 :(得分:2)

private LibraryBook book = new LibraryBook();

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

答案 2 :(得分:1)

您需要初始化Book属性。它永远不会设置为值,因此当您使用它时它将为null

你可以这样做。

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