【发布时间】: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#