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

本文关键字:字典 项目 CheckedListBox 检索 | 更新日期: 2023-09-27 18:06:26

我的表单上有一个checklistbox,我使用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或任何操作都只会返回为对象,我无法找出正确的方法来强制转换项目。

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

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