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

C# WinForms中如何从DataGridView内ComboBox.DataSource填充DataTable

C# WinForms DataGridViewComboBox数据源转DataTable方案

直接对ComboBox.DataSource做对应类型的显式转换即可,根据你绑定数据源的不同类型,对应处理方式如下:

1. 原始绑定源为DataTable

直接强转即可,代码示例:

// 强转数据源为DataTable
DataTable dataTable1 = comboBox.DataSource as DataTable;
// 判空后即可正常读取Seq列
if(dataTable1 != null)
{
    var seq1 = dataTable1.Rows[0]["Seq"];
}

注意:如果直接用(DataTable)comboBox.DataSource强制转换,数据源类型不匹配时会抛出异常,推荐用as关键字转换后判空

2. 原始绑定源为其他常见类型

绑定源为DataView

直接取DataView的Table属性即可:

DataView dv = comboBox.DataSource as DataView;
DataTable dataTable1 = dv?.Table;

绑定源为泛型集合List

可以用通用方法将集合转换为DataTable:

// 通用List转DataTable方法
public static DataTable ListToDataTable<T>(List<T> list)
{
    DataTable dt = new DataTable();
    // 构建列结构
    foreach (var prop in typeof(T).GetProperties())
    {
        dt.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
    }
    // 填充行数据
    foreach (T item in list)
    {
        DataRow row = dt.NewRow();
        foreach (var prop in typeof(T).GetProperties())
        {
            row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
        }
        dt.Rows.Add(row);
    }
    return dt;
}

调用示例:

List<你的实体类> dataList = comboBox.DataSource as List<你的实体类>;
DataTable dataTable1 = ListToDataTable(dataList);

3. DataGridView内嵌ComboBox的特殊说明

如果是DataGridView内的ComboBox列/单元格,需要从对应列或者编辑控件中取数据源:

  • 取列级别公共数据源:
DataGridViewComboBoxColumn comboCol = dataGridView1.Columns["你的ComboBox列名"] as DataGridViewComboBoxColumn;
DataTable dataTable1 = comboCol.DataSource as DataTable;
  • 取某一行正在编辑的ComboBox控件数据源:
if (dataGridView1.EditingControl is DataGridViewComboBoxEditingControl editCombo)
{
    DataTable dataTable1 = editCombo.DataSource as DataTable;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:24:03