Reputation: 146
How to check datatable select method returns datatable or not c#
e.g
datatable _dtt= dt.Select("fcm_id=1").CopyToDataTable();
above statement return all rows if fcm_id is 1 if datatable didn't have any row its throwing exception ....how to validate its row or not
e.g if(_dtt.Rows.Count > 0)
thank you
Upvotes: 1
Views: 5162
Reputation: 31
It is better to assign the select result to DataRow array and check the length of the array and then assign the array to the DataTable using CopyToDataTable().
DataTable _dtt = new DataTable();
DataRow[] dr = _dtt.Select("fcm_id=1");//assign the result of select() to datarow array
if (dr.Length > 0)//check if select() returns any data
_dtt = dr.CopyToDataTable(); //copy the rows of data to the datatable
Upvotes: 1
Reputation: 62488
You can do this using ternary operator to check if count is greater than 0 then call CopyToDataTable()
else return empty DataTable
or null
:
DataTable _dtt = dt.Select("fcm_id=1").Count() > 0 ? dt.Select("fcm_id=1").CopyToDataTable() :new DataTable();
or do with normal if
:
var result = dt.Select("fcm_id=1");
DataTable _dtt =null;
if (result.Count() > 0)
_dtt = result.CopyToDataTable();
Upvotes: 2