2011-04-19 21 views
-1

我有我的DataGridView.DataSource一個問題,它已經消耗了我大量的時間解決這個問題。以下是代碼:爲什麼我的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; 

當我調試代碼時,「resultQuery」和「finalResult」都包含我想要的結果。但是,當我設置「dgvSearch.DataSource」,結果不會出現在該行中,即使我嘗試都dgvSearch.DataSource = resultQuerydgvSearch.DataSource = finalResult。 DataGridView只是空的(列除外)。

我調試「dgvSearch」的代碼執行後,以確保數據源工作正常,且它。所有的結果都在DataSource中,但不知何故DataGridView將不會顯示它,儘管我已經調用了dgvSearch.show()

任何人都可以幫助我嗎?我覺得我想要自殺T_T。 非常感謝你提前。

+0

爲什麼你認爲應該有人幫助你,如果你不感謝他? – abatishchev 2011-04-20 11:27:14

回答

0

你打電話dgvSearch.DataBind()後設置其屬性DataSource

此外,直接在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(); 
+1

沒有dgvSearch.DataBind();在vs 2013 – 2015-09-01 05:50:27

8

的問題是,你設置你的LINQ查詢向上運行,但你有沒有實際執行它,甚至當您嘗試將其結果綁定到您的DataGridView。要執行您的LINQ查詢你需要「觸摸」的查詢結果,如在for環或致電ToList()。這稱爲「延期執行」。

因此改變,你綁定到該行,它應該工作(假設你的代碼是正確的,否則):

dgvSearch.DataSource = resultQuery.ToList(); 
+1

非常感謝,你的代碼是一個很好的工作^^ – Sammm 2011-04-21 17:24:52

相關問題