Compiling the Code
This example requires:
A form with a ListBox control named listBox1 and a Button control named button1. Set the button1
Click
event handler tobutton1_Click
.
Note: This code can also be used with a ComboBox control by substituting a ComboBox control named comboBox1 for the ListBox control and changing the code from listBox1 to comboBox1. |
Поиск элемента в элементе управления "ListBox"
В этом примере в элемент управления ListBox Windows Forms при загрузке формы добавляются некоторые элементы. Затем после нажатия кнопки в форме в ListBox выполняется поиск определенного элемента. Найденный элемент выделяется и отправляется сообщение об успешном выполнении поиска, которое содержит сам элемент и его индекс. В противном случае отправляется сообщение "Элемент не найден".
Пример
-----
Компиляция кода
Для этого примера необходимы следующие компоненты.
Форма с элементом управления ListBox с именем listBox1 и с элементом управления Button с именем button1. Задайте обработчику событий Click button1 значение button1_Click.
Примечание. Этот код также можно использовать с элементом управления ComboBox, заменив элемент управления ComboBox с именем comboBox1 для элемента управления на элемент управления ListBox и изменив в коде имя с listBox1 на comboBox1. |
Date and Time Controls
How to: Select a Range of Dates in a Calendar Control
This example selects a range of dates in a Windows Forms MonthCalendar control. In this example, when the user selects a date, the week is selected. You can use this code to select a range of dates in a week by changing the parameter of the AddDays method.
Example
private void monthCalendar1_DateSelected(object sender, System.Windows.Forms.DateRangeEventArgs e) { DateTime startDate = e.Start; startDate = startDate.AddDays(-(double)startDate.DayOfWeek); monthCalendar1.SelectionStart = startDate; monthCalendar1.SelectionEnd = startDate.AddDays(6); } |
Compiling the Code
This example requires:
A Windows Form with a MonthCalendar control named monthCalendar1. Set the
DateSelected
event handler of monthCalendar1 tomonthCalendar1_DateSelected
.
Отображение даты и времени
Выбор диапазона дат в элементе управления "Calendar"
В этом примере происходит выбор диапазона дат в элементе управления MonthCalendar Windows Forms. Если пользователь выделяет дату, в этом примере выделяется неделя. Чтобы выбрать диапазон дат в неделе, изменив параметр метода AddDays, можно использовать следующий код.
Пример
private void monthCalendar1_DateSelected(object sender, System.Windows.Forms.DateRangeEventArgs e) { DateTime startDate = e.Start; startDate = startDate.AddDays(-(double)startDate.DayOfWeek); monthCalendar1.SelectionStart = startDate; monthCalendar1.SelectionEnd = startDate.AddDays(6); } |
Компиляция кода
Для этого примера необходимы следующие компоненты.
Форма Windows Form с элементом управления MonthCalendar, которому задано имя monthCalendar1. Задайте обработчику событий DateSelected monthCalendar1 значение monthCalendar1_DateSelected.
How to: Retrieve a Date in a DateTimePicker Control
In this example, you select a meeting date in a Windows Forms DateTimePicker control. The selected meeting date and today's date are displayed in message boxes.
Example
private void button1_Click(object sender, System.EventArgs e) { // Display the selected date and time: MessageBox.Show("Your've selected the meeting date: " + dateTimePicker1.Value.Date);
// Display today's date and time: MessageBox.Show("Today is: " + DateTime.Today); } |
Compiling the Code
This example requires:
A Windows Form with a DateTimePicker control named
dateTimePicker1
and a Button control labeled Select a Meeting Date.Set the event handler of the button to
button1_Click
.
Извлечение даты в элементе управления "DateTimePicker"
В этом примере происходит выбор даты встречи в элементе управления DateTimePicker Windows Forms. Выбранная дата встречи и текущая дата будут отображены в окнах сообщений.
Пример
-----
Компиляция кода
Для этого примера необходимы следующие компоненты.
Форма Windows Form с элементом управления DateTimePicker, которому задано имя dateTimePicker1, и элемент управления Button с надписью Выбор даты встречи.
Задайте обработчику событий кнопки значение button1_Click.
How to: Display the Time in a Label
This example displays the current time in a Label.
Example
private void displayTime() { Label1.Text = DateTime.Now.ToShortTimeString(); } |
Compiling the Code
The form must contain a Labelnamed Label1.
Отображение времени в надписи
В этом примере текущее время отображается в Label.
Пример
private void displayTime() { Label1.Text = DateTime.Now.ToShortTimeString(); } |
Компиляция кода
Форма должна содержать Labelс именем "Label1".9
How to: Display the Date and Time in Your Application
You can display the date on a Windows Form by using calendar controls, such as the MonthCalendar control or a DateTimePicker control. The DateTimePicker control also enables you to display the time.
You can also use these controls to collect input from the user to use the date or time selected elsewhere in your application. The MonthCalendar control enables you to select a range of dates.
To display a date by using a MonthCalendar control
On the File menu, click New Project.
The New Project dialog box appears.
Click Windows Forms Application and then click OK.
Add a Label control to the form, with the default name label1.
Add a MonthCalendar control to the form, with the default name MonthCalendar1.
Double-click the form to add the default Load event handler in the Code Editor and add the following code. This code assigns the selected date (today's date) to the Text property of the label in short date format.
this.label1.Text = this.monthCalendar1.SelectionRange.Start.ToShortDateString();
Create a DateChanged event handler for the MonthCalendar1 control. You can do this by double-clicking the control in the designer.
Add the following code to the MonthCalendar_DateChanged event handler. This code sets the label to the selected date, but this time in long date format.
this.label1.Text = this.monthCalendar1.SelectionRange.Start.ToShortDateString();
Press F5 to run the program.
When the form opens, change the date by clicking a date in the MonthCalendar control.
Verify that the date is updated in the label.
- Введение в язык 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