The example starts a Windows application that displays the time zones defined on a system in a list box. The example then displays a dialog box that contains the value of the DisplayName property of the time zone object selected by the user.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim tzCollection As ReadOnlyCollection(Of TimeZoneInfo)
tzCollection = TimeZoneInfo.GetSystemTimeZones()
Me.timeZoneList.DataSource = tzCollection
End Sub
Private Sub OkButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OkButton.Click
Dim selectedTimeZone As TimeZoneInfo = DirectCast(Me.timeZoneList.SelectedItem(), TimeZoneInfo)
MsgBox("You selected the " & selectedTimeZone.ToString() & " time zone.")
End Sub
private void Form1_Load(object sender, EventArgs e)
{
ReadOnlyCollection<TimeZoneInfo> tzCollection;
tzCollection = TimeZoneInfo.GetSystemTimeZones();
this.timeZoneList.DataSource = tzCollection;
}
private void OkButton_Click(object sender, EventArgs e)
{
TimeZoneInfo selectedTimeZone = (TimeZoneInfo) this.timeZoneList.SelectedItem;
MessageBox.Show("You selected the " + selectedTimeZone.ToString() + " time zone.");
}
Most list controls (such as the System.Windows.Forms..::.ListBox or System.Web.UI.WebControls..::.BulletedList control) allow you to assign a collection of object variables to their DataSource property as long as that collection implements the IEnumerable interface. (The generic ReadOnlyCollection<(Of <(T>)>) class does this.) To display an individual object in the collection, the control calls that object's ToString method to extract the string that is used to represent the object. In the case of TimeZoneInfo objects, the ToString method returns the TimeZoneInfo object's display name (the value of its DisplayName property).
Note: |
|---|
Because list controls call an object's
ToString method, you can assign a collection of TimeZoneInfo objects to the control, have the control display a meaningful name for each object, and retrieve the TimeZoneInfo object that the user has selected. This eliminates the need to extract a string for each object in the collection, assign the string to a collection that is in turn assigned to the control's DataSource property, retrieve the string the user has selected, and then use this string to extract the object that it describes.
|