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

如何解决CS0029错误:ComboBox.ObjectCollection无法隐式转换为CheckedListBox.ObjectCollection

解决CS0029: 无法隐式转换ComboBox.ObjectCollection到CheckedListBox.ObjectCollection的问题

这个错误的根源很简单——你代码里的ObjectCollection默认引用的是System.Windows.Forms.CheckedListBox.ObjectCollection类型,但comboBox1.Items返回的是System.Windows.Forms.ComboBox.ObjectCollection,这两个是完全独立的集合类,编译器没办法自动把它们互相转换。

有两种简单的修复方式:

方式1:用var自动推断类型(推荐)

直接把ObjectCollection items = comboBox1.Items;改成var items = comboBox1.Items;,让编译器自己识别正确的集合类型,代码会更简洁且不易出错:

private void Button3_Click(object sender, EventArgs e)
{
    DataTable dataTable = new DataTable();
    // 用var自动推断正确的ComboBox.ObjectCollection类型
    var items = comboBox1.Items;
    foreach (var item in items)
    {
        MyClass myClass = (MyClass)item;
        string constr = string.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source =" + myClass.Path + ";Extended Properties = \"Excel 12.0; HDR=Yes;\"; ");
        OleDbConnection con = new OleDbConnection(constr);
        DataTable dt = new DataTable();
        using (OleDbCommand comm = new OleDbCommand())
        {
            comm.CommandText = "Select * From[" + myClass.TableName + "]";
            comm.Connection = con;
            using (OleDbDataAdapter da = new OleDbDataAdapter())
            {
                da.SelectCommand = comm;
                da.Fill(dt);
                dataTable.Merge(dt);
            }
        }
    }
    dataGridView1.DataSource = dataTable;
}

方式2:显式声明正确的集合类型

如果你想保持显式声明,就把ObjectCollection改成ComboBox.ObjectCollection,明确指定类型:

// 显式指定ComboBox的ObjectCollection类型
ComboBox.ObjectCollection items = comboBox1.Items;

这样编译器就能识别到正确的类型,错误就会消失啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:56:24