Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

c# - How to fix "The source contains no DataRows"?

Here i want to find the Matched Records From Two data tables. the code is

public DataTable textfiltering(DataTable dtfff, DataTable dtff)
{
   DataTable ds = (DataTable)Session["maintxt"];
   DataTable dts = (DataTable)Session["sectxt"];
   dtfff = ds;
   dtff = dts;     

   DataTable dtMerged = (from a in dtfff.AsEnumerable()
                          join b in dtff.AsEnumerable()
                          on a["contacts"].ToString() equals b["contacts"].ToString()
                          into g                                 
                          where g.Count()>0                             
                          select a).CopyToDataTable();
           return dtMerged;    

}

it gives "The source contains no DataRows" when Data tables does not contain Matched Records... How to rectify it..pls give your suggistions

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Two ways:

  1. either check if it contains rows with Enumerable.Any before you call CopyToDataTable
  2. use dtfff.Clone to create an empty DataTable with the same schema as the source table and use a loop to fill it from the LINQ query.

First approach:

var rows = from a in dtfff.AsEnumerable()
           join b in dtff.AsEnumerable()
           on a["contacts"].ToString() equals b["contacts"].ToString()
           into g
           where g.Count() > 0
           select a;
DataTable merged;
if (rows.Any())
   merged = rows.CopyToDataTable();
else
    merged = dtfff.Clone();
return merged;

Second approach:

DataTable merged = dtfff.Clone();
foreach (DataRow sourceRow in rows)
{
   merged.ImportRow(sourceRow);  // or add all fields manually
}
return merged;

I prefer the second approach since it only needs to execute the query once.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...