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 tobutton1_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 |
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 theForm1_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.
- Введение в язык c# и .Net Framework
- Язык c#
- Архитектура платформы .Net Framework
- Creating Your First c# Application
- To create a c# application
- Создание первого приложенияC#
- Создание приложения c#
- To create a c# console application
- Создание консольного приложения c#
- To create a c# Windows application
- Создание приложений Windows Forms на c#
- Introduction to Windows Presentation Foundation
- To create a wpf application
- Создание приложения wpf c#
- To create event handlers
- Создание обработчиков событий
- Designing a User Interface in Visual c#
- Adding Controls
- Создание пользовательского интерфейса в Visual c#
- Добавление элементов управления
- Setting Properties
- Handling Events
- Задание свойств
- Обработка событий
- How to: Use Button Controls
- Использование элемента управления "Button"
- To use buttons in a program
- Использование кнопок в программе
- How to: Call a Button's Click Event Programmatically
- To use buttons in a program
- Программный вызов события нажатия кнопки
- Использование кнопок в программе
- How to: Create a Group of Radio Buttons from a String Array
- Compiling the Code
- Example
- Создание группы переключателей из массива строк
- Создание непрямоугольной кнопки
- Компиляция кода
- How to: Display Text on a Windows Form
- To display text in a label
- Отображение текста в форме Windows Forms
- Отображение текста в надписи
- How to: Use TextBox Controls to Get User Input
- Использование элемента управления "TextBox" для получения вводимых данных
- To retrieve input typed in a text box
- Извлечение введенных в текстовое поле данных
- How to: Convert the Text in a TextBox Control to an Integer
- Диалоговые окна Извлечение данных из диалогового окна
- To create the main form of your application
- To create a dialog box
- Создание основной формы приложения
- Создание диалогового окна
- Retrieving Data from a Dialog Box
- To retrieve data from a dialog box.
- Извлечение данных из диалогового окна
- How to: Browse a Folder
- To display the folder browser dialog box
- Просмотр папки
- Отображение диалогового окна обозревателя папок
- How to: Save a File to a Folder
- To display the folder browser dialog box
- Сохранение файла в папку
- Отображение диалогового окна обозревателя папок
- How to: Display a List of Fonts
- To display the font dialog box
- Отображение списка шрифтов
- Отображение диалогового окна выбора шрифта
- How to: Display an OpenFileDialog Dynamically
- Отображение цветовой палитры
- Отображение диалогового окно выбора цвета
- ListBox and ComboBox Controls
- Compiling the Code
- Отображение даты и времени в приложении
- Отображение даты с помощью элемента управления "MonthCalendar"
- To display the time by using a DateTimePicker control
- Отображение времени с помощью элемента управления "DateTimePicker"
- How to: Determine the Span Between Two Dates
- Создание настраиваемого пользовательского интерфейса
- Добавление панелей инструментов в приложение Windows Forms
- To add a set of standard toolbar button
- Добавление набора стандартных кнопок панели инструментов
- How to: Create a Tooltip for a Control
- Compiling the Code
- Compiling the Code
- Добавление элементов управления Windows Forms во время выполнения
- Компиляция кода15
- Accessing and Displaying Data
- How to: Write Class Data to an xml File
- Example
- Compiling the Code
- Compiling the Code
- Robust Programming
- Чтение xml из файла
- Пример18
- Компиляция кода
- Надежное программирование
- How to: Read Class Data from an xml File
- Example
- Compiling the Code
- Robust Programming
- Чтение данных класса из xml-файла
- Пример19
- Компиляция кода
- Compiling the Code
- Компиляция кода
- Compiling the Code
- Robust Programming
- Рисование кривой в форме
- Компиляция кода
- Надежное программирование
- How to: Draw Outlined Shapes
- Example
- Compiling the Code
- Robust Programming
- Рисование контурных фигур
- Пример23
- Компиляция кода
- Добавление файлов мультимедиа в приложение
- Внедрение проигрывателя Windows Media в форму
- Добавление элемента управления "Windows Media Player" в панель элементов.
- To add the Windows Media Player control to a Windows Form
- Добавление элемента управления "Windows Media Player" в форму Windows Forms
- How to: Play Sounds in an Application
- To play an audio file
- Воспроизведение звука в приложении
- Воспроизведение аудиофайла
- Creating and Using Bitmaps and Icons
- How to: Create a Bitmap at Run Time
- Example
- Создание и использование точечных рисунков и значков
- Создание точечного рисунка во время выполнения
- Compiling the Code
- Compiling the Code
- Создание приложений wpf
- Создание пользовательского интерфейса для приложения wpf
- To create a wpf application
- Создание приложения wpf
- Adding Controls to the wpf Window You can add controls to the wpf window by dragging them from the Toolbox. To add a control to the wpf window
- Добавление элементов управления в окно wpf
- Добавление элемента управления в окно wpf
- Common wpf Controls
- Procedure To add a control to the wpf window
- Стандартные элементы управления wpf
- Процедура Добавление элемента управления в окно wpf
- Standard wpf Controls
- Стандартные элементы управления wpf
- How to: Create Event Handlers for wpf Controls
- To create an event handler for a button
- Создание обработчиков событий для элементов управления wpf
- Создание обработчика событий для кнопки
- Connecting to Data
- How to: Connect to a Database
- To add a connection to the Northwind database
- Подключение к данным
- Подключение к базе данных
- Добавление подключения к базе данных "Northwind"
- How to: Display Related Data on a Form
- To display related data on a form
- Отображение связанных данных в форме
- Отображение связанных данных в форме
- Using linq in c# Express
- Advantages of Using linq
- Использование linq в c# Express
- Преимущества использования linq
- C# Language Enhancements that Support linq
- Расширения языка c# для поддержки linq
- Writing linq Queries
- Linq to Objects
- Написание запросов linq
- Linq to Objects
- Linq to sql
- Linq to DataSet
- Linq to xml
- Linq to sql
- Linq to DataSet
- ЯзыкC# для начинающих Структура программы c#
- "Hello World" в стиле c#
- Using Directives and Namespaces
- Comments
- Директивыusingи пространства имен
- Комментарий
- Classes
- Console Input and Output
- Консольный ввод и вывод
- Program Structure and Flow of Execution
- Windows Forms Applications
- Структура программы и ход выполнения
- Приложения Windows Forms36
- Console Applications
- Namespaces
- Консольные приложения
- Пространства имен
- Namespace Shortcuts
- Creating Your Own Namespace
- Ускоренный доступ к содержимому пространства имен
- Создание собственного пространства имен
- Example
- Classes
- Classes vs. Objects
- Классы и объекты
- Static vs. Instance Members
- Classes vs. Files
- Члены экземпляра и статические члены37
- Классы и файлы
- Encapsulation
- Инкапсуляция
- Inheritance
- Polymorphism
- Наследование
- Полиморфизм
- Constructors
- Конструкторы
- Operator Overloading
- Compiling the Code
- Имитация параметров по умолчанию
- Компиляция кода
- Переменные и константы
- Constants
- Built-in Data Types
- Константы
- Встроенные типы данных
- Using Built-in Data Types
- Типы значений и ссылочные типы
- Boxing and Unboxing
- Упаковка и распаковка
- Performance issues
- Проблемы производительности
- Operators
- Decisions and Branching
- Remarks
- Выбор и ветвление
- Foreach Loops
- Циклы foreach
- For Loops
- Working with Strings
- Доступ к отдельным знакам
- Changing Case
- Смена регистра
- Comparisons
- Сравнения
- Splitting a String into Substrings
- Разделение строки на подстроки
- Using StringBuilder
- Использование класса StringBuilder
- How to: Generate Multiline String Literals
- Массивы и коллекции
- Массивы
- Одномерные массивы
- Multidimensional Arrays
- Jagged Arrays
- Многомерные массивы
- Массивы массивов
- Using the foreach Statement
- Использование оператора foreach
- Arrays of Objects
- Массивы объектов
- How to: Declare an Array
- Compiling the Code
- Robust Programming
- Инициализация массива
- Компиляция кода
- Коллекции
- How to: Iterate Through an Array
- Compiling the Code
- Компиляция кода
- Enumerations
- Перечисления
- More Advanced Enumeration Techniques
- Try and Catch
- Обработка ошибок и исключений
- Try и Catch
- Finally Blocks
- Using Exception Handling
- You can also cause your own exceptions using the throw keyword.
- Блоки finally
- How to: Catch an Exception
- Example
- Compiling the Code
- Перехват исключения
- Компиляция кода
- .Net Framework Conceptual Overview
- Общие сведения об основных понятиях платформы .Net Framework
- Features of the Common Language Runtime
- Возможности среды clr
- .Net Framework Class Library
- Библиотека классов платформы .Net Framework