I have a DropDown combo box that I am trying to use to emulate functionality that MS Outlook uses when adding/editing appointments. Given an Appt.StartTime of 9:00 AM, the EndTime DropDown combo is populated with items formatted as follows:
9:00 AM (0 minutes)
9:30 AM (30 minutes)
10:00 AM (1 hour)
10:30 AM (1.5 hours)
etc.
When I select an item from that list, I would like the editable portion of the control to only show "9:30 AM" (for instance) without the additional "(30 minutes)".
In the SelectedIndexChanged event, I can temporarily succeed using the following:
String sNewTime = this.cmbEndTime.Text;
sNewTime = sNewTime.Substring(0, sNewTime.IndexOf(" ("));
cmbEndTime.Text = sNewTime;
// confirm combo-box shows only Time
MessageBox.Show("Confirm");
As soon as the MessageBox is clicked away, however, the text is re-replaced with the text in the Items collection.
Any thoughts would be greatly appreciated. Thank you.
Loading
Mark HultzPosted Jan 19, 2007, 1:11 PM
This issue has now been resolved with the assistance of a VB.NET forum. In case anyone is interested, the solution is as follows:
Even though a combobox will allow the user to type a string into the control that does not exist in it's Items collection, the string MUST exist if trying to set the .Text property programmatically in an event like SelectedIndexChanged, DropDownClosed, etc.
Therefore, I scrapped the SelectedIndexChanged event and went with a DropDown event and a DropDownClosed event.
In DropDownClosed, I modify the text as desired, add it to the Items collection, and then set SelectedIndex to Items.Count-1.
In DropDown, I merely check to see if the last item was one that was added without the (?? timespan) suffix. If it is, I copy it's value to control's .Tag property and then remove it. (That way, if the user does not make a selection in DropDownClosed, the .Tag string is re-added to the Collection and SelectedIndex is set to that.)
Code for the events are as follows:
private void EndTime_DropDownClosed(object sender, EventArgs e)
{
int iIndex = cmbEndTime.SelectedIndex;
if (iIndex == -1) // user did not make a selection
{
cmbEndTime.Items.Add(cmbEndTime.Tag.ToString());
cmbEndTime.SelectedIndex = cmbEndTime.Items.Count - 1;
return;
}
String sNewTime = cmbEndTime.Items[iIndex].ToString();
sNewTime = sNewTime.Substring(0, sNewTime.IndexOf(" ("));
cmbEndTime.Items.Add(sNewTime);
cmbEndTime.SelectedIndex = cmbEndTime.Items.Count - 1;
}
private void EndTime_DropDown(object sender, EventArgs e)
{
int iIndex = cmbEndTime.Items.Count - 1;
if (cmbEndTime.Items[iIndex].ToString().IndexOf(" (") == -1)
{
// last item was added without (?? timespan) suffix
// in the previous DropDownClosed event. Get rid of it.
// (First, save it to .Tag -- This way, the value can
// be restored in DropDownClosed if the user closes
// the dropdown without actually making a selection)
cmbEndTime.Tag = cmbEndTime.Items[iIndex];
cmbEndTime.Items.Remove(cmbEndTime.Items[iIndex]);
}
}