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

Извлечение данных из диалогового окна

Передать данные из одной формы Windows Forms в другую можно несколькими способами. В этом примере Form1 будет передана конструктору Form2.

    1. Дважды щелкните кнопку ОК для создания обработчика событий по умолчанию Click. Перед добавлением кода в эту процедуру необходимо создать переменную для основной формы и новый конструктор для класса Form2.

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

Form1 mainForm;

public Form2(Form1 mainForm)

{

this.mainForm = mainForm;

InitializeComponent();

}

    1. Добавьте следующий код в обработчик событий Click кнопки okButton. Этот код очищает список, присваивает каждую строку текстового поля в Form2 массиву и затем добавляет каждый элемент массива текстовому полю в Form1.

      if (this.textBox1.Text != string.Empty)

      {

      mainForm.listBox1.Items.Clear();

      string[] stringsEntered = textBox1.Lines;

      for (int count = 0; count < stringsEntered.Length; count++)

      {

      mainForm.listBox1.Items.Add(stringsEntered[count]);

      }

      }

      this.Close();

    2. Right-click Form1 in Solution Explorer and click View Designer.

    3. Double-click the Add button to add the default Click event handler, and add the following code to create an instance of Form2 and display the form:

      Form2 subForm = new Form2(this);

      subForm.Show();

    4. Press F5 to run the code.

    5. When the form opens, click Add.

    6. When the dialog box opens, type the following list of colors, and press ENTER after each word.

Blue

Green

Yellow

Red

  1. Click OK.

  2. Verify that the data typed in the dialog box appears in the list box of Form1.

  3. Close the application.

  1. В обозревателе решений правой клавишей мыши щелкните элемент Form1 и выберите команду Открыть в конструкторе.

  2. Дважды щелкните кнопку Добавить для добавления обработчика событий по умолчанию Click и добавьте следующий код для создания экземпляра Form2 и отображения формы.

    Form2 subForm = new Form2(this);

    subForm.Show();

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

  4. После открытия формы щелкните Добавить.

  5. После открытия диалогового окна введите следующий список цветов, нажимая ВВОД после каждого слова.

Синий

Зеленый

Желтый

Красный

  1. Нажмите кнопку ОК.

  2. Убедитесь, что введенные в диалоговом окне данные появились в списке Form1.

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

How to: Browse a Folder

You can use the built-in FolderBrowserDialog component to enable users to browse 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 Label control to the form, and use the default name, Label1.

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

Property

Value

Name

folderPath

Text

Path

  1. Drag a FolderBrowserDialog component from the Dialogs tab of the Toolbox to the form.

folderBrowserDialog1 appears in the component tray.

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

  2. In the folderPath_Click event handler, add the following code to display the folder browser dialog box and display the selected path in the label.

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

    {

    this.label1.Text = folderBrowserDialog1.SelectedPath;

    }

  3. Press F5 to run the code.

  4. When the form appears, click Path, click a folder in the list, and then click OK.

  5. Verify that the selected path appears in the label.

  6. Close the application.

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