【问题标题】:Button to refresh combobox. "An item with the same key has already been added"用于刷新组合框的按钮。 “已添加具有相同密钥的项目”
【发布时间】:2013-10-16 00:20:45
【问题描述】:

我有一个从数据库返回对象列表的方法。我使用字典来连接 ID,并带有连接的字符串。我希望 FillComboBox 方法在单击后刷新组合框。这是 FillComboBox 代码:

private void FillComboBox()
    {
        List<Shift> shifts = null;
        shifts = ShiftMenager.GetAllAsString();
        if (shifts.Count != 0)
        {
            Dictionary<int, string> shiftsDict = null;
            shiftsDict = new Dictionary<int, string>();
            shiftsDict.Clear();

            foreach (Shift sh in shifts)
            {
                shiftsDict.Add(sh.id, sh.startDate.ToShortDateString() +
                " (" + sh.startDate.ToShortTimeString() + " - " +
                sh.endDate.ToShortTimeString() + ") - " + sh.employee);
            }

            shiftComboBox.DisplayMember = "Value";
            shiftComboBox.ValueMember = "Key";
            shiftComboBox.DataSource = new BindingSource(shiftsDict, null);
        }
        else
        {
            shiftComboBox.Enabled = false;
        }
    }

我把第一个 FillComboBox() 放在了

private void ShiftForm_Load(object sender, EventArgs e)
    {
        FillComboBox();
    }

第二个按钮点击事件:

private void RefreshButton_Click(object sender, EventArgs e)
    {
        FillComboBox();
    }

当表单加载时一切正常,但是当我单击按钮时,我收到一条消息“已添加具有相同键的项目。”。我真的找不到解决方法,在填充它之前尝试清除字典,首先分配 null 。 怎么了?谢谢。

【问题讨论】:

  • 将变量“shiftsDict”设置为空的代码,然后清除它什么也不做。只需初始化它。 Dictionary shiftsDict = new Dictionary();
  • 你可以使用 'shiftsDict[sh.id] = sh.startDate.ToShortDateString() + " (" + sh.startDate.ToShortTimeString() + " - " + sh.endDate.ToShortTimeString() + ") - " + sh.employee);'如果您不关心覆盖重复项,则将数据添加到字典中。此方法不会抱怨覆盖字典中的条目。它将自动创建/覆盖字典中的条目
  • 您可以通过启用异常中断来调试它:'Debug -> Exceptions: Enable 'Common Language Runtime Exceptions' -> enable 'Thrown'。
  • 可能是当您致电 GetAllAsString() 时,您的值班经理没有清除内部列表,导致字典在第二轮中被欺骗 ID 阻塞
  • 这就是问题所在。我从来没有真正想过这可能是一个问题。谢谢。

标签: c#


【解决方案1】:

这是调试问题的一种方法:

foreach (Shift sh in shifts)
{
  if (shiftsDict.ContainsKey(sh.id))
  {
    // code to log breakpoint on it to debug
  }
  else
  {
    shiftsDict.Add(sh.id, sh.startDate.ToShortDateString() +
      " (" + sh.startDate.ToShortTimeString() + " - " +
      sh.endDate.ToShortTimeString() + ") - " + sh.employee);
  }
}

【讨论】:

  • 我放置了一个消息框来代替评论。当我第一次单击按钮时,我得到的是:26、25、24、23、22、21,这没关系。但是当我第二次点击它时,我得到 26,25,24,23,22,21,26,25,24,23,22,21 这真的很奇怪,因为我真的不知道重复发生在哪里。
  • @user2832281 - 发布 ShiftMenager.GetAllAsString() 的代码,这就是错误所在。
【解决方案2】:

问题不是来自 Combobox。错误的来源是您正在使用的字典。我确定您的代码正在尝试添加具有相同已添加密钥的重复条目。

只需确保集合 shifts = ShiftMenager.GetAllAsString() 没有任何重复条目。

【讨论】:

    猜你喜欢
    • 2011-01-27
    • 2021-08-02
    • 2011-03-01
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多