I’ve got this code that uses winforms to get data passed between two forms (LibraryBookDialog.cs and MainForm.cs).
Here is the code for LibraryBookDialog.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;
namespace COMP2614HomeLab08
{
public partial class LibraryBookDialog : Form
{
private LibraryBook book;
public LibraryBook Book
{
get
{
if (book == null)
{
book = new LibraryBook();
}
return book;
}
set { book = value; }
}
public LibraryBookDialog()
{
InitializeComponent();
}
private bool validateData()
{
// code that validates user input data
}
private void buttonOk_Click(object sender, EventArgs e)
{
if (validateData())
{
try
{
LibraryBook book = new LibraryBook();
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);
}
}
}
}
}
Here is the code for MainForm.cs:
namespace COMP2614HomeLab08
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void buttonNew_Click(object sender, EventArgs e)
{
LibraryBookDialog dlg = new LibraryBookDialog();
dlg.ShowDialog();
if (dlg.DialogResult == DialogResult.OK)
{
listBoxLibraryBooks.Items.Add(dlg.Book);
}
dlg.Dispose();
}
private void MainForm_Load(object sender, EventArgs e)
{
listBoxLibraryBooks.DisplayMember = "Title";
}
}
}
The QUESTION: Why is it that when I add the LibraryBook book object to the listBox, I get a blank element. I mean, it is there, the element in the listBox exists, but I am not sure if the data has been passed from form to form. Why is this so?
You are using Book property of dialog but you’re not setting it with in the book dialog and your property getter returns a new instance if it is null. That is why you’re getting a blank entry.
Either change the book declaration to
Or at the end of creating the book set your class member book to this like so