Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
221 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...