Вы находитесь на странице: 1из 7

How to: Add and Clear Items in a ListBox Control

This example adds the contents of a Windows Forms TextBox control to a ListBox control when you click
button1, and clears the contents when you click button2.

Example
Copy Code

private void button1_Click(object sender,


System.EventArgs e)
{
listBox1.Items.Add("Sally");
listBox1.Items.Add("Craig");
}

private void button2_Click(object sender,


System.EventArgs e)
{
listBox1.Items.Clear();
}

Compiling the Code


This example requires:
A form with a ListBox control named listBox1 and two buttons named button1 and button2. Add
the button1Click event handler to button1_Click, and the button2Click event handler to
button2_Click.

How to: Determine the Selected Item in a ListBox Control


This example determines which item has been selected in a Windows Forms ListBox control.

Example
Copy Code

private void Form1_Load(object sender, System.EventArgs


e)
{
listBox1.Items.Add("One");
listBox1.Items.Add("Two");
listBox1.Items.Add("Three");
}

private void listBox1_SelectedIndexChanged(object

1
sender, System.EventArgs e)
{
if ((string)listBox1.SelectedItem == "Two")
MessageBox.Show((string)listBox1.SelectedItem);
}

Compiling the Code


This example requires:
A form named Form1 with a ListBox control named listBox1. Set the Load event handler of Form1
to Form1_Load. Set the SelectedIndexChanged event handler of listBox1 to
listBox1_SelectedIndexChanged.

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.

How to: Populate a ListBox Control with an Array of Strings


This example adds an array of strings to a ListBox control when the Windows Form opens.

Example
Copy Code

private void Form1_Load(object sender, System.EventArgs


e)
{
string [] myList = new string[4];

myList[0] = "One";
myList[1] = "Two";
myList[2] = "Three";
myList[3] = "Four";

listBox1.Items.AddRange(myList);
}

Compiling the Code


This example requires:
A form named Form1 with a ListBox control named listBox1. Set the Load event handler of Form1
to Form1_Load.

Note:
This code can also be used with a ComboBox control by substituting
a ComboBox control named comboBox1 for the ListBox control and

2
changing the code from listBox1 to comboBox1.

Robust Programming
The following conditions may cause an exception:
The array contains one or more null values.

How to: Search for an Item in a ListBox Control


In this example, you add some items to a Windows Forms ListBox control when the form is loaded. Then you
search the ListBox for a specific item by clicking a button on the form. If the item is found, it is selected and
a success message, which contains the item and its index, is sent by using a message box. Otherwise, an
"Item not found" message is sent.

Example
Copy Code

private void Form1_Load(object sender, System.EventArgs


e)
{
listBox1.Items.Add("Angelina");
listBox1.Items.Add("Isabella");
listBox1.Items.Add("Sarah");
}

private void button1_Click(object sender,


System.EventArgs e)
{
// Set the search string:
string myString = "Isabella";
// Search starting from index -1:
int index = listBox1.FindString(myString, -1);
if (index != -1)
{
// Select the found item:
listBox1.SetSelected(index,true);
// Send a success message:
MessageBox.Show("Found the item \"" + myString
+
"\" at index: " + index);
}
else
MessageBox.Show("Item not found.");
}

Compiling the Code

3
This example requires:
A form with a ListBox control named listBox1 and a Button control named button1. Set the
button1Click event handler to button1_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.

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. For more information,
see How to: Select a Range of Dates in a Calendar Control.

To display a date by using a MonthCalendar control


1. On the File menu, click New Project.
The New Project dialog box appears.
2. Click Windows Forms Application and then click OK.
3. Add a Label control to the form, with the default name Label1.
4. Add a MonthCalendar control to the form, with the default name MonthCalendar1.
5. 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.
C# Copy Code

this.label1.Text =

this.monthCalendar1.SelectionRange.Start.ToShortDateString(

6. Create a DateChanged event handler for the MonthCalendar1 control. You can do this by double-
clicking the control in the designer.
7. 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.
C# Copy Code

this.label1.Text =

this.monthCalendar1.SelectionRange.Start.ToShortDateString(

8. Press F5 to run the program.


9. When the form opens, change the date by clicking a date in the MonthCalendar control.
10. Verify that the date is updated in the label.

To display the time by using a DateTimePicker control


1. Add a DateTimePicker control to the form, with the default name DateTimePicker1.
2. Double-click the form to switch to the Code Editor.

4
3. Add the following code to the Form1_Load event handler. This code sets the format of the
control to display a time, instead of a date, and lets the user change the time that is
displayed.
C# Copy Code

this.dateTimePicker1.Format =
DateTimePickerFormat.Time;
this.dateTimePicker1.Width = 100;
this.dateTimePicker1.ShowUpDown = true;

4. Add a Button control to the form, and change the following properties.
Property Value

Name currentTime

Text Current Time


5. Double-click the button to add the default Click event handler.
6. Add the following code to set the time back to the current time.
C# Copy Code

this.dateTimePicker1.Value = DateTime.Now;

7. Press F5 to run the program.


8. When the form opens, change the time by selecting the hour, minute, or seconds and click the up or
down arrow.
9. Click Current Time to reset the control to the current time.

See Also

Concepts
Date and Time Controls
Designing a User Interface in Visual C# Express
Visual C# Guided Tour

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
Copy Code

private void monthCalendar1_DateSelected(object sender,


System.Windows.Forms.DateRangeEventArgs e)
{
DateTime startDate = e.Start;
startDate = startDate.AddDays(-
(double)startDate.DayOfWeek);
monthCalendar1.SelectionStart = startDate;
5
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 to monthCalendar1_DateSelected.

See Also

Concepts
Date and Time Controls
Designing a User Interface in Visual C# Express
Visual C# Guided Tour

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. For more information, see DateTimePicker
Control (Windows Forms).

Example
Copy Code

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.

How to: Display the Time in a Label


This example displays the current time in a Label.

Example
Copy Code

6
private void displayTime()
{
Label1.Text = DateTime.Now.ToShortTimeString();
}

Compiling the Code


The form must contain a Labelnamed Label1.

See Also

Concepts
Date and Time Controls

How to: Determine the Span Between Two Dates


This example calculates the difference in days between two dates and constructs a TimeSpan value for that
difference.

Example
Copy Code

DateTime oldDate = new DateTime(2002,7,15);


DateTime newDate = DateTime.Now;

// Difference in days, hours, and minutes.


TimeSpan ts = newDate - oldDate;

// Difference in days.
int differenceInDays = ts.Days;

System.Console.WriteLine("Difference in days: {0} ",


differenceInDays);
System.Console.ReadLine();

Compiling the Code


Copy the code and paste it into the Main method of a console application.

Вам также может понравиться