Sam*_*mmm -1 c# linq ienumerable datasource datagridview
我的DataGridView.DataSource有问题,它耗费了我很多时间来解决这个问题.以下是代码:
string[] queryWords = singleQuery.Split(' '); // Split the query words according the "space" character
// Compose the SQL select query
string selectClause = @"SELECT ID, CategoryID, Name, UnitID, Price, QuantityAgen, QuantityBanjer, QuantityMalalayang, QuantitySorong FROM Product WHERE ";
// Add the where clauses inside the SQL select query
for (int i = 0; i < queryWords.Length; i++)
{
selectClause += "(Name LIKE '%" + queryWords[i] + "%')";
if (i < queryWords.Length - 1)
selectClause += " AND ";
}
// Initiate the query and get the appropriate results
IEnumerable<SumberRejekiProgram.Code.Product> resultQuery = dbProduct.ExecuteQuery<SumberRejekiProgram.Code.Product>(selectClause);
var finalResult = from p in resultQuery
select new { Name = p.Name, Price = p.Price, Unit = p.Unit.Name };
// Bind the DataGridView according to the final query result in resultQuery variable
dgvSearch.DataSource = resultQuery;
Run Code Online (Sandbox Code Playgroud)
当我调试代码时,"resultQuery"和"finalResult"都包含我想要的结果.但是,当我设置"dgvSearch.DataSource"时,即使我尝试了两者dgvSearch.DataSource = resultQuery,结果也不会出现在行中dgvSearch.DataSource = finalResult.DataGridView只是空的(列除外).
我在代码执行后调试"dgvSearch"以确保DataSource正常工作.所有结果都在DataSource中,但不管怎么说,虽然我已经调用过,DataGridView也不会显示它dgvSearch.show().
谁可以帮我这个事?我觉得我想要自杀T_T.非常感谢你提前.
问题是您已将LINQ查询设置为运行但尚未实际执行它,即使您尝试将其结果绑定到DataGridView也是如此.要执行LINQ查询,您需要"触摸"查询结果,例如for循环或通过调用ToList().这称为"延期执行".
因此,更改绑定到此的行,它应该工作(假设您的代码是正确的):
dgvSearch.DataSource = resultQuery.ToList();
Run Code Online (Sandbox Code Playgroud)