The standard dialogs described in Lesson 8 make it easy to perform typical chores such as picking files, folders, colors, and fonts. Those dialogs can get you pretty far, but sometimes you may want a dialog that is customized for your application.
For example, you might want to display a dialog where the user can enter a new customer’s contact information (name, address, phone number, and hat size). It’s unlikely that any predefined standard dialog could ever handle that situation.
Fortunately, it’s easy to build custom dialogs. All you need to do is build a new form as described in Lesson 9, add a few buttons, and set a few properties.
In this lesson you learn how to build custom dialogs and make them as easy to use as the standard dialogs that come with C#.
Building a custom dialog is pretty easy. Simply add a new form to your project as described in Lesson 9 and give it whatever controls you need.
To allow the user to finish using the dialog, add one or more buttons. Some dialogs have a single OK button. Others have OK and Cancel buttons or some other combination of buttons. Because you’re creating the dialog, you can give it whatever buttons you like.
By convention, the buttons should go in the dialog’s lower-right corner. Figure 10.1 shows a very simple dialog that contains a single textbox where the user can enter a name.
To make using the dialog easier, you can set the form’s AcceptButton
and CancelButton
properties. These determine which button is triggered if the user presses Enter and Esc, respectively. Typically the AcceptButton
triggers the dialog’s OK or Yes button and the CancelButton
triggers the Cancel or No button.
A program uses the ShowDialog
method to display a dialog. This method returns a value that indicates which button the user clicked. As explained in Lesson 8, the program can check that return value to see what it should do with the dialog’s results. The examples in Lesson 8 checked that ShowDialog
returned the value DialogResult.OK
before processing the user’s selections.
The dialog form’s DialogResult
property determines what value the call to ShowDialog
returns. For example, you could use the following code to make the dialog’s OK Button
set the form’s DialogResult
property to DialogResult.OK
to tell the calling program that the user clicked the OK button:
// Return OK to ShowDialog.
private void okButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
}
Setting the form’s DialogResult
property not only determines the return result but also closes the dialog so the call to ShowDialog
returns and the calling code can continue.
That means you can set the dialog’s return result and close the dialog in a single line of code. Typing one line of code should be no real hardship, but believe it or not, there’s an even easier way to close the dialog.
If you set a Button
’s DialogResult
property, the Button
automatically sets the form’s DialogResult
property when it is clicked. For example, suppose you set the cancelButton
’s DialogResult
property to DialogResult.Cancel
. When the user clicks the Button
, it automatically sets the form’s DialogResult
property to DialogResult.Cancel
so the form automatically closes. That lets you set the return value and close the form without typing any code at all.
If you think setting one Button
property is still too much work, you can even avoid that, at least for the Cancel button. When you set a form’s CancelButton
property, C# automatically sets that Button
’s DialogResult
property to DialogResult.Cancel
.
Note that when you set the form’s AcceptButton
property, C# does not automatically set the Button
’s DialogResult
property. The assumption is that the OK Button
might need to validate the data the user entered on the form before it decides whether to close the dialog. For example, if the user doesn’t fill in all required fields, the OK Button
might display a message asking the user to fill in the remaining fields instead of closing the dialog.
If you don’t want to perform any validation, you can simply set the OK Button
’s DialogResult
property to DialogResult.OK
.
A program uses a custom dialog in exactly the same way that it uses a standard dialog. It creates, initializes, and displays the dialog. It checks the return result and takes whatever action is appropriate.
There’s a slight difference in how the program creates the dialog because you can add standard dialogs to a form at run time and you can’t do that with custom dialogs. To use a custom dialog, the code needs to create a new instance of the dialog’s form as described in Lesson 9.
The following code shows how a program might display a new customer dialog:
// Let the user create a new customer.
private void newCustomerButton_Click(object sender, EventArgs e)
{
// Create and display a NewCustomerDialog.
NewCustomerDialog newCustomerDialog;
newCustomerDialog = new NewCustomerDialog();
if (newCustomerDialog.ShowDialog() == DialogResult.OK)
{
// … Create the new customer here …
}
}
The code declares a variable to refer to the dialog and makes a new instance of the dialog. It displays the dialog by using its ShowDialog
method and checks the return result. If the user clicks OK, the program takes whatever steps are needed to create the new customer, such as adding a record to a database.
In this Try It, you build and use the simple custom dialog shown in Figure 10.2. The dialog lets you enter a name. If you enter a non-blank value and click OK, the main form adds the name you entered to a ListBox
.
This Try It also gives you a little practice using the ListBox
control, showing how to add and remove items.
In this lesson, you:
Button
be the form’s AcceptButton
and the Delete Comedian Button
be the form’s CancelButton
.AcceptButton
and CancelButton
properties in the obvious way.Button
display the dialog. If the dialog returns DialogResult.OK
, add the new comedian’s name to the ListBox
.Button
remove the currently selected comedian from the ListBox
.Button
, hide the dialog and return DialogResult.Cancel
.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, hide the dialog and return DialogResult.OK
.ListBox
’s Items.Add
method to add a new item to the ListBox
.ListBox
’s Items.Remove
method to remove the selected item (which is identified by the SelectedItem
property).nameTextBox.Text.Length == 0
to see whether the name entered on the dialog is blank. You can use code similar to the following to take one action if the length is 0 and another if it is not. Notice the new else
part of the if
statement. If the condition is true, the statements after the if
clause are executed. If the condition is false, the statements after the else
clause are executed. (Lesson 18 covers if
and else
in more detail.)
if (nameTextBox.Text.Length == 0)
{
… Display a message here …
}
else
{
… Return DialogResult.OK here …
}
nameTextBox
control’s Modifiers
property to Public
so the main form’s code can use it.Button
be the form’s AcceptButton
and the Delete Comedian Button
be the form’s CancelButton
.
Label
, ListBox
, and two Button
s roughly as shown in Figure 10.2.ListBox
’s Anchor
property to Top, Bottom, Left, Right
. Set the Button
s’ Anchor
properties to Top, Right
.AcceptButton
property to the New Comedian Button
. Set its CancelButton
property to the Delete Comedian Button
.AcceptButton
and CancelButton
properties in the obvious way.
Label
, TextBox
, PictureBox
, and two Button
s roughly as shown in Figure 10.2.TextBox
’s Anchor
property to Top, Left, Right
. Set the Button
s’ Anchor
properties to Bottom, Right
.PictureBox
and set its Anchor
property to Top, Bottom, Left
. Set its SizeMode
property to Zoom
.AcceptButton
property to the OK Button
. Set its CancelButton
property to the Cancel Button
.FormBorderStyle
property to FixedDialog
, set its ControlBox
property to False
, and set its ShowInTaskbar
property to False
.Button
display the dialog. If the dialog returns DialogResult.OK
, add the new comedian’s name to the ListBox
.
Button
. Use code similar to the following:// Create a new comedian entry.
private void newComedianButton_Click(object sender, EventArgs e)
{
NewComedianDialog newComedianDialog;
newComedianDialog = new NewComedianDialog();
if (newComedianDialog.ShowDialog() == DialogResult.OK)
{
// Add the new comedian.
comedianListBox.Items.Add(
newComedianDialog.nameTextBox.Text);
}
}
Button
remove the currently selected comedian from the ListBox
.
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 crashes.
Button
, hide the dialog and return DialogResult.Cancel
.
CancelButton
property to this Button
, C# sets the Button
’s DialogResult
property to DialogResult.Cancel
so the button automatically sets the return result and closes the dialog.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, hide the dialog and return DialogResult.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");
}
else
{
DialogResult = DialogResult.OK;
}
}
ShowDialog
method returns True
as in this code:
if (newComedianDialog.ShowDialog().Value)
{
…
}
Button
, set the Button
’s IsDefault
property to True
.Button
, set the Button
’s IsCancel
property to True
.Button
’s code should set DialogResult = true
.ResizeMode
to NoResize
.ShowInTaskbar
to False
.Button
even if no comedian is selected. To fix that, copy the program you built for the Try It and add the following event handler to enable or disable the button when the ListBox
’s selection changes:
// Enable the Delete Comedian button if an entry is selected.
private void comedianListBox_SelectedIndexChanged(
object sender, EventArgs e)
{
deleteComedianButton.Enabled =
(comedianListBox.SelectedIndex >= 0);
}
Hint: Don’t forget to disable the Button
initially.
Button
has an IsEnabled
property instead of an Enabled
property.)Button
is enabled when the text in the TextBox
is non-blank. Hints:
TextBox
’s TextChanged
event handler.Button
when the text is blank, the OK Button
doesn’t need a Clicked
event handler. Just set its DialogResult
property to OK
.Button
s don’t have a DialogResult
property. The OK Button
still needs a Click
event handler, but all it needs to do is set the form’s DialogResult
property.)Label
s as shown on the Contact Information form in Figure 10.3. When the user clicks the Edit Button
, the program should display the Edit Contact dialog shown in Figure 10.3 to let the user change the values. If the user clicks OK, the copy the new values back into the main form’s Label
s.
MessageBox.Show
is almost perfect but you’d like to change the Button
s’ text. Create a program that defines the message dialog shown in Figure 10.4.
The main program should set the Label
’s text, the dialog’s title, and the Button
s’ text. Make the Accept Button
return DialogResult.OK
and make the Decline Button
return DialogResult.Cancel
. Make the main form display different messages depending on whether the user clicked Accept or Decline.
Hints:
PictureBox
.FormBorderStyle
=FixedDialog
, ControlBox
=False
, and ShowInTaskbar
= False
.
Title
property.Label
control doesn’t support word wrapping. To let the dialog wrap text, use a TextBlock
with TextWrapping
set to Wrap
.Button
s should display the same dialog to let the user select foreground and background colors. Only update the main form’s colors if the user clicks OK. Don’t worry about initializing the dialog to show the current values before displaying it. (Hint: You built a program that lets the user select colors with scrollbars for Lesson 4’s Try It.)
Border
control.ScrollBar
s share the following event handler:
// Display the color sample.
private void redScrollBar_Scroll(object sender,
System.Windows.Controls.Primitives.ScrollEventArgs e)
{
redLabel.Content = redScrollBar.Value.ToString("0");
greenLabel.Content = greenScrollBar.Value.ToString("0");
blueLabel.Content = blueScrollBar.Value.ToString("0");
Color color = Color.FromRgb(
(byte)redScrollBar.Value,
(byte)greenScrollBar.Value,
(byte)blueScrollBar.Value);
sampleBorder.Background = new SolidColorBrush(color);
}
Button
, the form displays the dialog. When the user clicks one of the thumbnail images, the dialog displays a border around that image’s PictureBox
. If the user clicks OK, the dialog closes and the main form displays the selected image at full scale.
Hints:
BorderStyle
property to Fixed3D
for that PictureBox
and None
for the others.PictureBox
on the dialog and set its Image
property equal to that of the clicked PictureBox
.PictureBox
es.Button
if a picture has been selected.Button
’s TabStop
property to False
. (To see why, set it equal to True
, run the program, select a picture, and press Enter.)Image
control on the main window and display the selected picture in it.Image
controls don’t have a BorderStyle
property. Indicate the selected Image
control by setting its Opacity
property to 1. Set the other Image
controls’ Opacity
properties to 0.5.3.16.218.221