0

データベースからオブジェクトのリストを返すメソッドがあります。Dictionary を使用して、連結された文字列で 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();
    }

ボタンクリックイベントの2番目:

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

フォームが読み込まれるとすべて正常に動作しますが、ボタンをクリックすると、「同じキーを持つアイテムが既に追加されています。」というメッセージが表示されます。私は本当にそれを回避する方法を見つけることができません.それを埋める前に辞書をクリアしようとしました.最初にnullを割り当ててください. なにが問題ですか?ありがとう。

4

2 に答える 2