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

Использование элемента управления "TextBox" для получения вводимых данных

С помощью элемента управления TextBox можно как отображать текст, так и получать его от пользователя. Введенные пользователем данные в TextBox можно получить с помощью свойства Text. По умолчанию свойство Multiline TextBox имеет значение false. Это означает, что пользователь не может нажимать клавишу ВВОД для создания нескольких строк текста в TextBox. Для включения этой возможности установите для свойства Multiline значение true.

To retrieve input typed in a text box

  1. On the File menu, click NewProject.

  2. In the New Project dialog box, click Windows Forms Application, and then click OK.

A new Windows Forms project opens.

  1. From the Toolbox, drag a TextBox control onto the form, and change the following properties in the Properties window:

    Property

    Value

    Name

    inputText

    Multiline

    True

    Size

    175, 90

  2. Add a Button control next to the text box, and change the following properties:

    Property

    Value

    Name

    retrieveInput

    Text

    Retrieve

  3. Double-click the button to create the retrieveInput_Click event handler, and add the following code:

    MessageBox.Show(this.inputText.Text);

  4. Press F5 to run the program.

  5. Type multiple lines of text in the text box, and then click Retrieve.

  6. Verify that the message displays all the text that you typed in the text box.

Извлечение введенных в текстовое поле данных

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

  2. В диалоговом окне Создание проекта выберите Приложение Windows Forms, а затем нажмите кнопку ОК.

Откроется новый проект Windows Forms.

  1. Перетащите элемент управления TextBox из панели элементов в форму и измените следующие свойства в окне Свойства.

    Свойство

    Значение

    Имя

    inputText

    Многострочность

    True

    Размер

    175, 90

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

    Свойство

    Значение

    Имя

    retrieveInput

    Текст

    Извлечь

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

    MessageBox.Show(this.inputText.Text);

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

  5. Введите несколько строк текста в текстовом поле и нажмите кнопку Извлечь.

  6. Убедитесь, что сообщение отображает весь текст, введенный в текстовое поле.

How to: Convert the Text in a TextBox Control to an Integer

When you provide a TextBox control in your application to retrieve a numeric value, you often have to convert the text (a string) to a numeric value, such as an integer. This example demonstrates two methods of converting text data to integer data.

Example

int anInteger;

anInteger = Convert.ToInt32(textBox1.Text);

anInteger = int.Parse(textBox1.Text);

Compiling the Code

This example requires:

  • A TextBox control named textBox1.

Robust Programming

The following conditions may cause an exception:

  • The text converts to a number that is too large or too small to store as an int.

  • The text may not represent a number.

Преобразование текста в элементе управления "TextBox" в целое число

Если в приложении используется элемент управления TextBox для извлечения числовых значений, часто приходится преобразовывать текст (строку) в числовое значение, например целое число. В этом примере показано два способа преобразования текстовых данных в целочисленные.

Пример

int anInteger;

anInteger = Convert.ToInt32(textBox1.Text);

anInteger = int.Parse(textBox1.Text);

Компиляция кода3

Для этого примера необходимы следующие компоненты.

  • Элемент управления TextBox с именем textBox1.

Надежное программирование

Исключение может возникнуть при следующих условиях.

  • Текст преобразуется в число, которое слишком велико или мало для сохранения в качестве int.

  • Возможно, текст не представляет число.

How to: Set the Selected Text in a TextBox Control

This example programmatically selects text in a Windows Forms TextBox control and retrieves the selected text.

Example

private void button1_Click(object sender, EventArgs e)

{

textBox1.Text = "Hello World";

textBox1.Select(6, 5);

MessageBox.Show(textBox1.SelectedText);

}

Compiling the Code

This example requires:

  • A form with a TextBox control named textBox1 and a Button control named button1. Set the Click event handler of button1 to button1_Click.

Note:

The code can also be used with a RichTextBox control by substituting a RichTextBox control named richTextBox1 for the TextBox control and changing the code from textBox1 to richTextBox1.

Robust Programming

In this example you are setting the Text property before you retrieve the SelectedText value. In most cases, you will be retrieving text typed by the user. Therefore, you will want to add error-handling code in case the text is too short.

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