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

如何处理System.InvalidCastException:无法将String转为MyListBoxItem?

解决ListBox SelectedItem无法转换为MyListBoxItem的问题

问题根源

你的listBox1的Items集合里实际存的是System.String类型对象,不是MyListBoxItem实例——这就是强制转换时抛出InvalidCastException的原因。大概率是你往ListBox里加的是字符串(比如调用listBox1.Items.Add("xxx")),而非自定义的MyListBoxItem对象。

具体解决步骤

1. 正确添加MyListBoxItem实例到ListBox

把原来添加字符串的代码替换成添加自定义对象:

// 错误写法:直接加字符串
// listBox1.Items.Add("测试内容");

// 正确写法:添加MyListBoxItem对象
listBox1.Items.Add(new MyListBoxItem { Message = "测试内容" });

2. 重写MyListBoxItem的ToString()(推荐)

默认情况下ListBox会显示对象的类型全名,重写ToString()可以让ListBox直接展示你想要的文本:

public class MyListBoxItem
{
    public string Message { get; set; }

    // 重写后ListBox会显示Message的内容
    public override string ToString()
    {
        return Message;
    }
}

3. 安全转换SelectedItem获取Message

在listBox1_SelectedIndexChanged事件里用安全转换,避免异常:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    // 先判断是否有选中项
    if (listBox1.SelectedItem == null) return;

    // 用as关键字安全转换,失败返回null
    var selectedItem = listBox1.SelectedItem as MyListBoxItem;
    if (selectedItem != null)
    {
        // 成功获取Message属性
        string targetMessage = selectedItem.Message;
        // 这里写你的后续逻辑,比如弹窗显示
        MessageBox.Show(targetMessage);
    }
    else
    {
        // 处理转换失败的情况
        MessageBox.Show("选中项不是有效的自定义类型");
    }
}

4. 已添加字符串的补救方案

如果因为历史原因ListBox里已经存了字符串,没法重新添加对象,可以直接用选中的字符串当Message:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (listBox1.SelectedItem == null) return;

    var selectedStr = listBox1.SelectedItem as string;
    if (selectedStr != null)
    {
        // 直接用字符串作为Message
        MessageBox.Show(selectedStr);
    }
}

补充:转换字符串失败的排查

你说转换为string也没成功,大概率是SelectedItem为null(没有选中任何项),所以一定要先判断listBox1.SelectedItem != null,再进行转换操作。

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 01:47:17