logo
Учебник_ПОА

Compiling the Code

This example requires:

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 выполняется поиск определенного элемента. Найденный элемент выделяется и отправляется сообщение об успешном выполнении поиска, которое содержит сам элемент и его индекс. В противном случае отправляется сообщение "Элемент не найден".

Пример

-----

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

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

Примечание.

Этот код также можно использовать с элементом управления 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:

Отображение даты и времени

Выбор диапазона дат в элементе управления "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);

}

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

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

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:

Извлечение даты в элементе управления "DateTimePicker"

В этом примере происходит выбор даты встречи в элементе управления DateTimePicker Windows Forms. Выбранная дата встречи и текущая дата будут отображены в окнах сообщений.

Пример

-----

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

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

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

  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, with the default name label1.

  3. Add a MonthCalendar control to the form, with the default name MonthCalendar1.

  4. 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();

  5. Create a DateChanged event handler for the MonthCalendar1 control. You can do this by double-clicking the control in the designer.

  6. 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();

  7. Press F5 to run the program.

  8. When the form opens, change the date by clicking a date in the MonthCalendar control.

  9. Verify that the date is updated in the label.