c# - check if a DataGridView has a DataSource -
i have module imports excel file
, display contents in datagridview object
. @ same time, have module export contents of datagridview object
's datasource datatable
excel file
.
how can check if datagridview has datasource not doing if(datagridview1.rows.count == 0){}
condition.
this because have noticed if user imports or open empty excel file
datagridview object
still display single column
.
this why want try , check if datagridview object
has datasource
im looking code
if(datagridview1.datasource == true) { // datasource if found or bound } else { //do datasource not found or not bound }
edit -- using code filter empty datasources:
assuming that:
var dtlist = new dictionary<string, datatable>() { { "datagridview1", (datatable) (datagridview1.datasource) }, { "datagridview2", (datatable) (datagridview2.datasource) }, { "datagridview3", (datatable) (datagridview3.datasource) }, { "datagridview4", (datatable) (datagridview4.datasource) } };
and datagridview1
, datagridview3
has no datasource
or datagridview object
empty. run code below filter , remove 2 empty datatable
:
//filter , remove empty datatable(s) var remlist = new list<string>(); foreach(var dt in dtlist) { try { var dump = dt.value.gettype().tostring(); } catch(exception ex) { remlist.add(dt.key); } } foreach(var rem in remlist) { dtlist.remove(rem); }
with code, able filter out other empty datatable
dtlist object
. of course, seeking better formula this. yeah, hope can tips , codes. thanks
i suggest write code validate empty rows in datagridview
avoid exporting empty rows.
you validating datasource
null, doubt how different validating rows count.
since mentioned see empty row being added when importing excel, avoid exporting empty datagridview excel doing validation.
datatable source = datagridview1.datasource datatable; var emptyrows = source.asenumerable() .all(r=> r.itemarray.all(x=> x == dbnull.value)); if(!emptyrows) { //export }