Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_for_Beginners.doc
Скачиваний:
28
Добавлен:
23.11.2019
Размер:
2.4 Mб
Скачать

Просмотр папки

Чтобы пользователи могли выбирать папки, можно использовать встроенный компонент FolderBrowserDialog. Чтобы отобразить диалоговое окно, используйте метод ShowDialog. Затем с помощью поля DialogResult..::.OK можно проверить, нажал ли пользователь кнопку ОК.

Отображение диалогового окна обозревателя папок

    1. В меню Файл выберите команду Создать проект.

Откроется диалоговое окно Создание проекта.

    1. Выберите элемент Приложение Windows Forms и нажмите кнопку ОК.

    2. Добавьте в форму элемент управления Label и именем по умолчанию Label1.

    3. Добавьте элемент управления Button в форму и измените следующие свойства в окне Свойства.

Свойство

Значение

Имя

folderPath

Текст

Путь

  1. С вкладки Диалоговые окна панели элементов перетащите в форму компонент FolderBrowserDialog.

В области компонентов появится компонент folderBrowserDialog1.

  1. Дважды щелкните кнопку, чтобы создать в редакторе кода обработчик событий по умолчанию.

  2. В обработчик событий folderPath_Click добавьте следующий код для отображения диалогового окна обозревателя папок и отображения выбранного пути в надписи.

    if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)

    {

    this.label1.Text = folderBrowserDialog1.SelectedPath;

    }

  3. Нажмите клавишу F5 для выполнения кода.

  4. В открывшейся форме нажмите кнопку Путь, выберите папку в списке и нажмите кнопку ОК.

  5. Убедитесь, что выбранный путь появился в надписи.

  6. Закройте приложение.

How to: Save a File to a Folder

You can use the built-in SaveFileDialog component to enable users to save a file to a folder. To display a dialog box, you use the ShowDialog method. You can then check whether the user clicked the OK button by using the DialogResult..::.OK field.

To display the folder browser dialog box

  1. On the File menu, click New Project.

The New Project dialog box appears.

  1. Click Windows Forms Application and then click OK.

  2. Add a RichTextBox control to the form, leaving the default name, RichTextBox1.

  3. Add a Button control to the form, and change the following properties in the Properties window:

    Property

    Value

    Name

    saveTextFile

    Text

    Save As

  4. Add a SaveFileDialog component to the form.

saveFileDialog1 appears in the component tray.

  1. Double-click the button to add the default event handler in the Code Editor.

  2. In the saveTextFile_Click event handler, add the following code to display the Save As dialog box. This code saves the text typed in the RichTextBox control to a text file at the specified location.

    saveFileDialog1.Filter = "txt files (*.txt)|*.txt";

    if(saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK

    && saveFileDialog1.FileName.Length > 0)

    {

    richTextBox1.SaveFile(saveFileDialog1.FileName,

    RichTextBoxStreamType.PlainText);

    }

  3. Press F5 to run the code.

  4. When the form appears, type some text in the rich text box.

  5. Click Save As and then browse to a folder where you want to save the text file.

  6. Specify a name for the text file, and then click OK.

  7. Verify that the text file exists at the specified location.

  8. Close the application.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]