Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# ПІДРУЧНИКИ / c# / Manning - Windows.forms.programming.with.c#.pdf
Скачиваний:
108
Добавлен:
12.02.2016
Размер:
14.98 Mб
Скачать

8.1.3CREATING A YESNO DIALOG

As an alternate example, what happens when an error occurs while saving an album? We could simply display an OK dialog as we did while opening an album. This would just duplicate the previous code, so we will do something different. Instead, we will allow the user to save the album under an alternate file name. This permits the user to save the album to an alternate location that is less likely to fail, or retry the save to the same location. The new message box is shown in figure 8.3.

Figure 8.3

This message box is displayed when an exception occurs in the menuSave_Click method.

The steps required to generate this message dialog are shown in the following table:

HANDLE EXCEPTION IN MENUSAVE_CLICK METHOD

 

Action

Result

 

 

 

1

Locate the menuSave_Click

private void menuSave_Click

 

method in the MainForm.cs file.

(object sender, System.EventArgs e)

 

 

{

 

 

. . .

 

 

 

2

Enclose the code to save the

else

 

album in a try block.

{

 

 

try

 

 

{

 

 

// Save album in current file

 

 

_album.Save();

 

 

_bAlbumChanged = false;

 

 

}

 

 

 

3

Catch any exception that occurs.

catch (Exception ex)

 

 

{

 

 

 

4

Within the catch block, display

string msg = "Unable to save file {0}"

 

the dialog and record the

+ " - {1}\nWould you like to save"

 

selected button.

+ " the album in an alternate file?";

 

DialogResult result

 

 

 

 

= MessageBox.Show(this,

 

 

String.Format(msg,

 

 

_album.FileName, ex.Message),

 

 

"Save Album Error",

 

 

MessageBoxButtons.YesNo,

 

 

MessageBoxIcon.Error,

 

 

MessageBoxDefaultButton.Button2);

 

 

 

5

If the user wishes to save under

if (result == DialogResult.Yes)

 

an alternate name, prompt the

{

 

user for the new file name.

menuSaveAs_Click(sender, e);

 

}

 

 

 

How-to

}

 

Use the Save As menu handler.

. . .

 

}

 

 

 

 

 

MESSAGE BOXES

229

Соседние файлы в папке c#