为什么我的datagridviewdatasource不绘制行

本文关键字:绘制 datagridviewdatasource 我的 为什么 | 更新日期: 2023-09-27 17:50:26

我有一个问题与我的DataGridView。它消耗了我很多时间来解决这个问题。下面是代码:

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;

当我调试代码时,"resultQuery"answers"finalResult"都包含我想要的结果。但是,当我设置"dgvSearch。数据源",结果不出现在行中,即使我尝试了dgvSearch.DataSource = resultQuerydgvSearch.DataSource = finalResult。DataGridView是空的(除了列)。

我调试"dgvSearch"后的代码执行,以确保数据源工作正常,它确实。所有的结果都在DataSource,但不知怎的,DataGridView不会显示它,虽然我已经调用了dgvSearch.show()

有谁能帮我一下吗?我觉得我真想自杀。非常感谢。

为什么我的datagridviewdatasource不绘制行

问题是,你已经设置你的LINQ查询运行,但你还没有实际执行它,甚至当你试图绑定它的结果到你的DataGridView。要执行LINQ查询,您需要"触摸"查询结果,例如在for循环中或通过调用ToList()。这被称为"延迟执行"。

所以改变绑定到this的行,它应该工作(假设你的代码是正确的):

dgvSearch.DataSource = resultQuery.ToList();

设置DataSource属性后是否调用dgvSearch.DataBind() ?

另外,在SQL中直接使用字符串连接是非常非常糟糕的(快速搜索"SQL注入")。要么使查询参数化,要么将其滚入Linq查询。根据您使用的特定提供程序,这可能工作,也可能不工作:

// Initiate the query and get the appropriate results
var resultQuery = from p in dbProduct.Product
                  select new { Name = p.Name, Price = p.Price, Unit = p.Unit.Name };
// Add the where clauses
for (int i = 0; i < queryWords.Length; i++)
{
    resultQuery = resultQuery.Where(p => p.Name.Contains(queryWords[i]));
}
// Bind the DataGridView according to the final query result in resultQuery variable
dgvSearch.DataSource = resultQuery;
dgvSearch.DataBind();

您应该尝试调用Page。

您也可以尝试使用此处文档中的bindingsource:

http://msdn.microsoft.com/en-us/library/fbk67b6z.aspx Y210