如何将bindingdatasource强制转换为datatable

本文关键字:转换 datatable bindingdatasource | 更新日期: 2024-07-23 08:09:44

我正试图使用以下代码将绑定数据源强制转换为数据表

BindingSource bs = (BindingSource)gvSideMember.DataSource;
        DataTable tCxC = (DataTable)bs.DataSource;

throws error无法将绑定源强制转换为数据表

然后我尝试了这个代码

 private DataTable GetDataTableFromDGV(DataGridView dgv)
    {
        var dt = ((DataTable)dgv.DataSource).Copy();
        foreach (DataGridViewColumn column in dgv.Columns)
        {
            if (!column.Visible)
            {
                dt.Columns.Remove(column.Name);
            }
        }
        return dt;
    }

它再次向我显示相同的错误

  DataTable dt = new DataTable();
        DataSourceSelectArguments args = new DataSourceSelectArguments();
        DataView dv = new DataView();
        dv = (DataView)SqlDataSource1.Select(args);
        dt = dv.ToTable();

但是我不知道DataSourceSelectArguments的基类是什么?所以我不能,我该怎么做这个石膏?

如何将bindingdatasource强制转换为datatable

看起来你的bs.DataSource实际上是另一个BindingSource,所以你可以试试这个:

var source = bs.DataSource;
while(source is BindingSource){
  source = ((BindingSource)source).DataSource;
}
if(source is DataTable){
  var table = (DataTable) source;
}//else there is not any DataTable we can extract.

这是我的解决方案,如果您使用BindingSource作为n个子级,它也能工作。

    public static DataTable Table(this DataGridView dgv)
    {
        DataTable dt;
        if (dgv.DataSource is BindingSource)
            dt = ((BindingSource)dgv.DataSource).Table();
        else if (dgv.DataSource is DataSet)
            dt = ((DataSet)dgv.DataSource).Tables[dgv.DataMember];
        else if (dgv.DataSource is DataTable)
            dt = (DataTable)dgv.DataSource;
        else
            dt = null;
        return dt;
    }
    public static DataTable Table(this BindingSource bs)
    {
        var bsFirst = bs;
        while (bsFirst.DataSource is BindingSource)
            bsFirst = (BindingSource)bsFirst.DataSource;
        DataTable dt;
        if (bsFirst.DataSource is DataSet)
            dt = ((DataSet)bsFirst.DataSource).Tables[bsFirst.DataMember];
        else if (bsFirst.DataSource is DataTable)
            dt = (DataTable)bsFirst.DataSource;
        else
            return null;
        if (bsFirst != bs)
        {
            if (dt.DataSet == null) return null;
            dt = dt.DataSet.Relations[bs.DataMember].ChildTable;
        }
        return dt;
    }