Skip to main content
 首页 » 编程设计

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

2024年02月23日14yxwkf

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

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

有什么想法吗?

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"); 
} 

请您参考如下方法:

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

However, if you try to get the SelectedText value in a SelectedIndexChanged or SelectedValueChanged event handler, the property returns an empty string. This is because, at the time of these events, the previous SelectedText value has been cleared and the new value has not yet been set. To retrieve the current value in a SelectedIndexChanged or SelectedValueChanged event handler, use the SelectedItem property instead.

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

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