You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Dictionary绑定到ListBox后SelectedIndexChanged触发异常的原因排查

问题分析与解决方案

问题根源

触发的Sequence contains no elements异常,核心原因是ListBox的SelectedItem并非字典的Key字符串:
当你将FileList.ToList()绑定到ListBox时,实际绑定的是List<KeyValuePair<string, string>>集合,ListBox的SelectedItem是完整的KeyValuePair对象,直接调用ToString()会返回类似[KeyName, ValuePath]的格式,而非字典的Key值。这就导致Where(x => x.Key == ...)找不到匹配项,调用First()时因序列为空抛出异常。

修复方案

方案1:直接转换SelectedItem为KeyValuePair

修改SelectedIndexChanged事件代码,正确提取选中项的键值对:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    var listBox = sender as ListBox;
    // 校验选中项类型并转换
    if (listBox?.SelectedItem is KeyValuePair<string, string> selectedItem)
    {
        pictureBox1.Image = System.Drawing.Image.FromFile(selectedItem.Value);
    }
}

方案2:设置DisplayMember和ValueMember(更规范)

在构造函数绑定数据时,指定ListBox的显示字段和值字段,后续直接通过SelectedValue获取图片路径:

public Form1()
{
    InitializeComponent();
    string g = File.ReadAllText(@"d:\rectangles.txt");
    FileList = JsonConvert.DeserializeObject<Dictionary<string, string>>(g);
    
    // 指定显示字典的Key,值为字典的Value
    listBox1.DisplayMember = "Key";
    listBox1.ValueMember = "Value";
    listBox1.DataSource = FileList.ToList(); 
}

对应的事件代码:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    var listBox = sender as ListBox;
    // 校验选中值是否有效
    if (listBox?.SelectedValue is string imagePath && !string.IsNullOrEmpty(imagePath))
    {
        pictureBox1.Image = System.Drawing.Image.FromFile(imagePath);
    }
}

额外注意事项

  • 空值校验:避免ListBox未选中项或选中项无效时触发异常
  • 图片路径校验:确保JSON文件中的图片路径正确且文件存在,可添加try-catch块处理图片加载失败的情况:
try
{
    pictureBox1.Image = System.Drawing.Image.FromFile(imagePath);
}
catch (Exception ex)
{
    MessageBox.Show($"图片加载失败:{ex.Message}");
}

内容的提问来源于stack exchange,提问作者jhon last

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 13:20:28