【问题标题】:Getting the old selected index in Winform's Combo box在 Winform 的组合框中获取旧的选定索引
【发布时间】:2012-08-18 17:06:27
【问题描述】:

我有一个组合框(winform)。这个组合框有一些项目(例如 1,2,3,4)。

现在,当我更改此组合中的选择时,我希望知道旧索引新索引

我如何得到这个?

我希望避免的可能方法。

  1. 添加 enter 事件,缓存当前索引,然后在选择索引更改时获取新索引。

  2. 使用事件发送者收到的选定文本/选定项属性。

我最想要的:

  1. 在收到的事件参数中,我想要类似的东西:

    e.OldIndex; e.newIndex;

    目前在 SelectionIndex Change 事件中接收到的事件参数是完全没用的。

  2. 我不想使用多个事件。

  3. 如果 C# 不提供此功能,我可以将我的事件作为事件参数传递旧索引和新索引吗?

【问题讨论】:

标签: c# winforms combobox


【解决方案1】:

这似乎是重复的

ComboBox SelectedIndexChanged event: how to get the previously selected index?

没有内置任何内容,您需要监听此事件并在类变量中跟踪。

但这个答案似乎提出了一种扩展组合框以跟踪前一个索引的明智方法 https://stackoverflow.com/a/425323/81053

【讨论】:

    【解决方案2】:

    1-制作整数列表
    2-绑定一个按钮切换到上一个屏幕(按钮名称“prevB”)
    3-根据代码中的描述更改组合框索引

    //initilize List and put current selected index in it
    
    List<int> previousScreen = new List<int>();
    previousScreen.Add(RegionComboBox.SelectedIndex);    
    
    //Button Event
     private void prevB_Click(object sender, EventArgs e)
        {
            if (previousScreen.Count >= 2)
            {
                RegionComboBox.SelectedIndex = previousScreen[previousScreen.Count - 2];
            }
        }
    

    【讨论】:

      【解决方案3】:

      您需要将 ComboBox 替换为以下控件:

      public class AdvancedComboBox : ComboBox
      {
          private int myPreviouslySelectedIndex = -1;
          private int myLocalSelectedIndex = -1;
      
          public int PreviouslySelectedIndex { get { return myPreviouslySelectedIndex; } }
      
          protected override void OnSelectedIndexChanged(EventArgs e)
          {
              myPreviouslySelectedIndex = myLocalSelectedIndex;
              myLocalSelectedIndex = SelectedIndex;
              base.OnSelectedIndexChanged(e);
          }
      }
      

      现在您可以获得PreviouslySelectedIndex 属性。

      【讨论】:

        【解决方案4】:

        您可以使用 YourComboBox.Tag(或其他未使用的字符串/int 属性)来存储旧的选定索引...

        【讨论】:

        • 感谢您的贡献!但请注意,原作者明确希望避免缓存(除非我误解了您的答案)。如果您在答案中包含代码 sn-ps 也很棒。
        【解决方案5】:

        我用这样的一对

        comboBox.SelectedItem 新项目

        comboBox.SelectionBoxItem 旧项

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-08-11
          • 1970-01-01
          • 2013-06-29
          相关资源
          最近更新 更多