C#:在 SelectedIndexChange 事件处理程序中设置 ComboBox 文本值?

Cur*_*tis 1 c# combobox winforms

我有一个包含 DropDown 组合框的 winform,用户可以在其中输入购买日期。

组合框中的项目是“选择日期”,它会显示一个日历,以便用户可以选择一个日期,“今天”和“上周”。如果用户选择“今天”或“上周”,我想将下拉控件的文本值设置为该日期字符串。我试图在 SelectedIndexChanged 处理程序中执行此操作,但没有骰子。DropDown 列表只显示一个空白字段。

有任何想法吗?

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");
}
Run Code Online (Sandbox Code Playgroud)

Jef*_*tes 5

SelectedText在 ComboBox 的可编辑部分中选择的属性文本。MSDN 状态

但是,如果您尝试SelectedTextSelectedIndexChangedSelectedValueChanged事件处理程序中获取 值 ,该属性将返回一个空字符串。这是因为,在这些事件发生时,先前的SelectedText 值已被清除,而新值尚未设置。要在SelectedIndexChangedSelectedValueChanged事件处理程序中检索当前值 ,请改用该SelectedItem属性。

由于SelectedText属性与属性密切相关SelectedItem,因此更改所选文本可能会导致所选索引发生更改。正如您所观察到的,这可能会导致重入问题,从而阻止一项或两项操作成功完成。在这种情况下,诀窍是延迟更新,直到当前事件完成。在 WinForms 中,这可以使用BeginInvoke方法和适当的委托来完成,该委托将执行延迟的工作(在 WPF 应用程序中,这是使用Dispatcher当前控件的 执行的)。

对于此任务,您可能需要考虑使用与组合下拉列表不同的控件,因为您的用例并不真正符合从列表中进行选择的想法。听起来您真正需要的东西更像是菜单和文本显示。