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

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.

Установка выделения текста в элементе управления "TextBox"

В этом примере в элементе управления Windows Forms TextBox текст выделяется программным путем, а затем извлекается.

Пример

private void button1_Click(object sender, EventArgs e)

{

textBox1.Text = "Hello World";

textBox1.Select(6, 5);

MessageBox.Show(textBox1.SelectedText);

}

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

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

  • Форма с элементом управления TextBox с именем textBox1 и с элементом управления Button с именем button1. Задайте обработчику событий Click для button1 значение button1_Click.

Примечание.

Код также можно использовать с элементом управления RichTextBox, заменив элемент управления TextBox на элемент управления RichTextBox с именем richTextBox1 и изменив в коде имя с textBox1 на richTextBox1.

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

В этом примере перед извлечением значения SelectedText устанавливается свойство Text. В большинстве случаев извлекается текст, введенный пользователем. Поэтому если текст слишком короток, в код рекомендуется добавить обработчик ошибок.

How to: Format Characters in a RichTextBox Control

This example writes a sentence, which contains three words in three different font styles (bold, italic, and underlined), to an existing RichTextBox control.

Example

richTextBox1.Rtf = @"{\rtf1\ansi This text is in \b bold\b0, " +

@"this is in \i italics\i0, " +

@"and this is \ul underlined\ul0.}";

Compiling the Code

This example requires: A RichTextBox control named richTextBox1.

Robust Programming

The rich text format is very flexible, but any errors in the format lead to errors in the displayed text.

Форматирование знаков в элементе управления "RichTextBox"

В этом примере выполняется запись предложения, содержащего три слова, написанных разными шрифтами (полужирным, курсивом и с подчеркиванием), в существующий элемент управления RichTextBox.

Пример

richTextBox1.Rtf = @"{\rtf1\ansi This text is in \b bold\b0, " + @"this is in \i italics\i0, " +

@"and this is \ul underlined\ul0.}";

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

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

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

Расширенный текстовый формат очень гибок, но любая ошибка в формате приведет к ошибкам в отображаемом тексте.

How to: Load Text into a RichTextBox Control

This example loads a text file that a user selects in the OpenFileDialog. The code then populates a RichTextBox control with the file's contents.

Example

// Create an OpenFileDialog object.

OpenFileDialog openFile1 = new OpenFileDialog();

// Initialize the filter to look for text files.

openFile1.Filter = "Text Files|*.txt";

// If the user selected a file, load its contents into the RichTextBox.

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

richTextBox1.LoadFile(openFile1.FileName, RichTextBoxStreamType.PlainText);

Compiling the Code

This example requires:

  • A RichTextBox control named richTextBox1. Insert the code segment into the Form1_Load method. When you run the program, you will be prompted to select a text file.

Загрузка текста в элемент управления "RichTextBox"

В этом примере выполняется загрузка текстового файла, выбранного пользователем в OpenFileDialog. Затем код заполняет элемент управления RichTextBox содержимым файла.

Пример

// Create an OpenFileDialog object.

OpenFileDialog openFile1 = new OpenFileDialog();

// Initialize the filter to look for text files.

openFile1.Filter = "Text Files|*.txt";

// If the user selected a file, load its contents into the RichTextBox.

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

richTextBox1.LoadFile(openFile1.FileName, RichTextBoxStreamType.PlainText);

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

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

  • Элемент управления RichTextBox с именем richTextBox1. Вставьте сегмент кода в методForm1_Load.6При выполнении программы будет выведен запрос на выбор текстового файла.

Dialog Boxes

How to: Retrieve Data from a Dialog Box

Dialog boxes enable your program to interact with users and retrieve data that users have entered in the dialog box for use in your application. There are several built-in dialog boxes that you can use in your applications. You can also create your own dialog boxes.

A common task in Windows Forms development is displaying a dialog box to collect information when a user clicks a button on the main form of an application. You can see an example of this in the Visual C# Express Edition IDE. When you add a ListBox control to a form, you can click the Items property in the Properties window to display a dialog box. This dialog box enables you to quickly type text on separate lines of a text box. The application then adds each line of text to ListBox control when you click OK. If you want to let users add their own items to a list box in your application, you can create your own string editor dialog box.

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