c# - Linq query to Datasource,InvalidOperationException -


i'm trying query table simple ms access database, local file, query works can't set datasoruce:

 ienumerable<datarow> result = row in bdspitaldataset.tabel.asenumerable()                      row.varsta >= &&                            row.varsta <= down &&                            row.cnp.startswith(convert.tostring(sex))                      select row;          datatable resulttable = result.copytodatatable<datarow>();          tabelbindingsource.datasource = resulttable;          datagridview1.update(); 

so invalidoperationexception @ datatable resulttable = result.copytodatatable<datarow>(); operation. idea?

i assume[1](edit: confirmed op) don't exception @ tabelbindingsource.datasource = resulttable @ result.copytodatatable<datarow>() because query doesn't contain datarows. columns of new datatable derived datarow.table.columns, if there no rows there no informations.

the exception documented:

invalidoperationexception:

  • a datarow in source sequence has state of deleted.
  • the source sequence not contain datarow objects.
  • a datarow in source sequence null.

you can use any check before:

if(result.any()) {     datatable resulttable = result.copytodatatable<datarow>();     tabelbindingsource.datasource = resulttable;     datagridview1.update(); } 

a more efficient approach:

datatable resulttable = bdspitaldataset.tabel.clone(); foreach(datarow row in result.rows)     resulttable.loaddatarow(row.itemarray, false); 

more efficicient because result.any() needs execute query determine if there's @ least 1 row, result.copytodatatable<datarow>() executes second time.


[1] why assume you've mentioned wrong error-line? because of comment:

an unhandled exception of type 'system.invalidoperationexception' occurred in system.data.datasetextensions.dll


Comments