How to cast bindingdatasource to datatable?

2019-01-20 20:27发布

I'm trying to cast the bindingdatasource to datatable using this code

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

throws error unable to cast bindingsource to datatable

then i tried this code

 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;
    }

it again show me same error

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

but i don't know what is the base class of DataSourceSelectArguments ? So I can't how can i do this cast?

2条回答
The star\"
2楼-- · 2019-01-20 20:53

This is my solution which also works if you are using BindingSource as n child level.

    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;
    }
查看更多
我只想做你的唯一
3楼-- · 2019-01-20 21:06

Looks like your bs.DataSource is actually another BindingSource, so you can try this:

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.
查看更多
登录 后发表回答