Mik*_*ike 26 c# linq datatable dataset
DataTable dt = ds.Tables[4].AsEnumerable()
    .Where(x => ((DateTime)x["EndDate"]).Date >= DateTime.Now.Date)
    .CopyToDataTable();
ds.Tables[4] 有行,但它抛出异常 
"源不包含DataRows."
知道如何处理或摆脱这种异常吗?
J. *_*een 37
ds.Tables[4]可能,但你的linq查询的结果可能不会,这可能是抛出异常的地方.拆分方法链接以使用临时参数,这样您就可以确定错误发生的位置.它还可以帮助您在调用之前检查现有行CopyToDataTable()并避免所述异常.
就像是
DataTable dt = null;
var rows = ds.Tables[4].AsEnumerable()
    .Where(x => ((DateTime)x["EndDate"]).Date >= DateTime.Now.Date);
if (rows.Any())
    dt = rows.CopyToDataTable();
另一种选择是ImportRow在a上使用该功能DataTable
DataTable dt = ds.Tables[4].Clone();
var rows = ds.Tables[4].AsEnumerable()
    .Where(x => ((DateTime)x["EndDate"]).Date >= DateTime.Now.Date);
foreach (var row in rows)
    dt.ImportRow(row);
只需分成两行
var rowSources = ds.Tables[4].AsEnumerable()
           .Where(x => ((DateTime)x["EndDate"]).Date >= DateTime.Now.Date);
if(rowSources.Any())
{
   DataTable dt = rowSources.CopyToDataTable();
   ... code that deals with the datatable object
}
else
{
   ... error message ?
}
这样可以检查结果是否包含任何DataRow,如果是,则可以调用CopyToDataTable方法。
| 归档时间: | 
 | 
| 查看次数: | 29538 次 | 
| 最近记录: |