C#: Setting ComboBox text value in SelectedIndexChange event handler?
I have a winform containing a DropDown combobox, where the user can enter a purchase date.
The items in the combobox are 'select date', which brings up a calendar so the user can choose a date, 'today' and 'last week'. If the user chooses 'today' or 'last week', I want to set the text value of the dropdown control to that date string. I'm trying to do this in the SelectedIndexChanged handler, but no dice. The DropDown list just shows a blank field.
Any ideas?
private void comboBoxPurchased_SelectedIndexChanged(object sender, EventArgs e)
{
Types.ComboInfo info = (Types.ComboInfo)comboBoxPurchased.SelectedItem;
DateTime newDate = stock.PurchaseDate;
switch ((Types.PurchasedDate)info.id)
{
case Types.PurchasedDate.PickCustom:
//popup a date dialog and let the user choose the date
PopupCalendar p = new PopupCalendar();
if (p.ShowDialog() == DialogResult.OK)
// show date in combobox
newDate = p.Date;
break;
case Types.PurchasedDate.Today:
newDate = DateTime.Now;
break;
case Types.PurchasedDate.WithinLastWeek:
newDate = DateTime.Now.AddDays(-7);
break;
case Types.PurchasedDate.WithinLastMonth:
newDate = DateTime.Now.AddMonths(-1);
break;
}
// re-create combobox items with new purchase date
/开发者_如何学运维/PopulatePurchaseDateCombo(newDate);
comboBoxPurchased.SelectedText = date.ToString("MMMM d, yyyy");
comboBoxPurchased.Text = date.ToString("MMMM d, yyyy");
}
The SelectedText
property text that is selected in the editable portion of a ComboBox. MSDN states:
However, if you try to get the
SelectedText
value in aSelectedIndexChanged
orSelectedValueChanged
event handler, the property returns an empty string. This is because, at the time of these events, the previousSelectedText
value has been cleared and the new value has not yet been set. To retrieve the current value in aSelectedIndexChanged
orSelectedValueChanged
event handler, use theSelectedItem
property instead.
Because the SelectedText
property is closely tied to the SelectedItem
property, changing the selected text can lead to a change in the selected index. This can lead to re-entrancy problems that can prevent one or both of the operations from successfully completing, as you have observed. In this case, the trick is to delay your update until the current event is complete. In WinForms, this can be done using the BeginInvoke
method and an appropriate delegate that will perform the deferred work (in WPF applications, this is performed using the Dispatcher
of the current control).
You may want to consider using a different control than a combo dropdown for this task as your use-case doesn't really fit with the idea of selecting from a list. It sounds like what you really need is something more like a menu and a text display.
精彩评论