检索 CheckedListBox 选定的项目作为字典

Retrieving CheckedListBox Selected Items as Dictionary

我的表单上有一个检查列表框,我使用字典填充它。当我填充该框时它工作正常但是当我尝试检索所选对象时我不知道如何将其作为字典来做。

我用来填充它的代码:

reader = widgetSelection.ExecuteReader();
while (reader.Read())
{
 widgets.Add(reader.GetInt32(0), reader.GetString(reader.GetOrdinal("name")));
}

foreach (var widget in widgets)
{
    chbWidgets.Items.Add(widget);
}

它填充得很好,但任何尝试执行 foreach 或任何从中进行的尝试都只会作为对象返回,我无法找出投射项目的正确方法。任何帮助都会很棒。

如果您的示例中的 widgetsDictionary<int, string>,则 chbWidgets.Items.Add(widget) 会将 KeyValuePair<int, string> 添加到 Items 集合。要获取所选项目,您可以使用 chbWidgets.CheckedItems.Cast<KeyValuePair<int, string>>().