120
LESSON 10 Building Custom dialogs
Make the New Comedian
Button display the dialog. If the dialog returns DialogResult.OK,
add the new comedian’s name to the
ListBox.
1. Create an event handler for the New Comedian Button. Use code similar to the
following:
// Create a new comedian entry.
private void newComedianButton_Click(object sender, EventArgs e)
{
NewComedianForm newComedianDialog;
newComedianDialog = new NewComedianForm();
if (newComedianDialog.ShowDialog() == DialogResult.OK)
{
// Add the new comedian.
comedianListBox.Items.Add(
newComedianDialog.nameTextBox.Text);
}
}
Make the Delete Comedian
Button remove the currently selected comedian from the
ListBox.
1. Create an event handler for the Delete Comedian Button. Use code similar to the
following:
// Remove the currently selected comedian.
private void deleteComedianButton_Click(object sender, EventArgs e)
{
comedianListBox.Items.Remove(comedianListBox.SelectedItem);
}
This makes the ListBox remove the currently selected item. Fortunately if there is no
selected item, the
ListBox does nothing instead of crashing.
When the user clicks the dialog’s Cancel button, close the form and return
DialogResult.Cancel.
1. You don’t need to do anything else to make this work. When you set the dialog’s
CancelButton property to this Button, Visual C# sets the Button’s DialogResult
property to
DialogResult.Cancel so the button automatically sets the return result
and closes the dialog.
When the user clicks the dialog’s OK
Button, check the entered name’s length. If the length
is 0, display a message asking the user to enter a name. If the length is greater than 0, close
the form and return
DialogResult.OK.
1. Create an event handler for the dialog’s OK Button. Use code similar to the following:
// Make sure the comedian’s name isn’t blank.
private void okButton_Click(object sender, EventArgs e)
{
if (nameTextBox.Text.Length == 0)
{
MessageBox.Show(“Please enter a comedian’s name”);
}
596906c10.indd 120 4/7/10 12:32:25 PM