如何使用linq查询绑定gridview [英] How to bind the gridview using linq query
问题描述
我想通过使用带有某些where条件的linq查询从数据表中选择特定行,然后将所选值绑定到该网格中.谁能帮我解决这个问题.这是我的代码
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
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
推荐答案
原因是在声明中
The reason is that in the statement
grdPt02Documents.DataSource = resultRow ;
resultRow
超出范围,因为它在foreach
loop范围内声明.
此外,声明
the resultRow
is out of scope as it is declared within the scope of foreach
loop.
Further, the statement
foreach (string list in DocList)
{
var resultRow = (from Data in (dtDocuments.AsEnumerable())
where Data.Field<string>("DocumentId") ==list.ToString()
select Data);
}
将提供与DocList
中最后一个字符串相对应的行,因为它将替换之前找到的所有resultRow.
list
已经是string
并且列表.ToString()是多余的.
我认为以下代码可用于问题中所述的目的
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
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();
这篇关于如何使用linq查询绑定gridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!