GridView.DataSource as DataTable sets to null in asp.net

I set my gridview.datasource to a datatable variable as shown below:

DataTable dt = gvPaymentHistory.DataSource as DataTable; 

GvPaymentHistory.DataSource has a record, however dt is null after this line is executed. How to transfer Datasource data to dt?

EDIT

A DataSource is a List collection of a class object. This is not a DataSet.

+6
source share
3 answers

An easy way is to save the grid data source to the view source when you bind data to the grid and then retrieve it from the view source every time you need it.

 Gridview.Datasource = yourdatasource; ViewState["mydatasource"] = yourdatasource; 

When retrieving

 DataTable dt = ViewState["mydatasource"] as DataTable; 

Hope this solves your problem.

+2
source

EDIT

if bidning is a list than try

 List<CodeEntity> data= gvPaymentHistory.DataSource as List<CodeEntity>; 

or

  List<CodeEntity> codes = (List<CodeEntity>)gvPaymentHistory.DataSource; 

check this

 if(gvPaymentHistory.DataSource is DataTable) DataTable dt = gvPaymentHistory.DataSource as DataTable; if(gvPaymentHistory.DataSource is DataView ) DataView dv = gvPaymentHistory.DataSource as DataView; 
0
source

Try this method: use BindingSource

 BindingSource bs = (BindingSource)gvPaymentHistory.DataSource; DataTable dt =((YourDataSetType) (bs.DataSource)).Tables[0]; 
0
source

Source: https://habr.com/ru/post/921949/


All Articles