Click here to Skip to main content
15,559,682 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I want to select the particular rows from a datatable by using the linq query with some where condition and then I want to bind the selected values into that grid. Can any one help me to solve this problem. Here is my code

C#
DataTable dtDocuments =GetDocuments();
string DocumentList = getDocumentList(KeyId); 
string[] DocList = DocumentList.Split(',');
foreach (string list in DocList)
{
var resultRow = (from Data in (dtDocuments.AsEnumerable())
where Data.Field<string>("DocumentId") ==list.ToString()
select Data);
}
grdPt02Documents.DataSource = resultRow ;  // It showing the error as resultrow is not found
grdPt02Documents.DataBind();




Thanks in Advance
Posted
Updated 11-May-12 16:59pm
v2
Comments
VJ Reddy 12-May-12 7:00am    
Thank you for accepting the solution.

1 solution

The reason is that in the statement
C#
grdPt02Documents.DataSource = resultRow ;

the resultRow is out of scope as it is declared within the scope of foreach loop.
Further, the statement
XML
foreach (string list in DocList)
{
var resultRow = (from Data in (dtDocuments.AsEnumerable())
where Data.Field<string>("DocumentId") ==list.ToString()
select Data);
}

will give the rows corresponding to the last string in DocList as it will replace any resultRow found earlier.
The list is already a string and list.ToString() is redundant.
I think the following code can be used for the purpose stated in the question
C#
string[] docIds = DocumentList.Split(',');
var resultTable = (dtDocuments.AsEnumerable().Where (d => docIds
        		.Any (i => d.Field<string>("DocumentId")
        		.Equals(i.Trim(), StringComparison.InvariantCulture)))
        		.Select (d =>d )).CopyToDataTable();
 
Share this answer
 
v2
Comments
Shahin Khorshidnia 12-May-12 3:46am    
+5
VJ Reddy 12-May-12 3:56am    
Thank you, Shahin.
Sandeep Mewara 12-May-12 3:58am    
Nice explanation. 5!
VJ Reddy 12-May-12 4:06am    
Thank you, Sandeep.
Member 7946563 12-May-12 7:00am    
Hi,

Thanks for ur reply it worked fine for me.Can u please give the same code for not equal to that document Id.

Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900