2012-07-27 41 views
0

這裏篩選的LINQ to SQL查詢是我的代碼:如何通過使用文本框輸入

private void textBox1_TextChanged(object sender, EventArgs e) 
    { 
     //************************************** 
     int aa = textBox1.Text.Length; 

     var qry = (from p in dc.Products 
        where p.ProductName.Substring(aa) == textBox1.Text.Trim() 
        select p).ToList(); 
     productDataGridView.DataSource = qry; 
    } 

當我在文字框中輸入一個字母DataGrid中成爲空

+0

使用'p.ProductName.Contains(textBox1.Text.Trim())'而不是'p.ProductName.Substring(aa)== textBox1.Text.Trim()' – Chandu 2012-07-27 14:01:03

+0

@Chandu p.ProductName.Contains textBox1.Text.Trim())意味着結果應該包含在文本框中的任何位置輸入的字母,我需要的是查詢返回的項目應該在文本框中有文本作爲第一個字符 – 2012-07-27 14:10:57

回答

2
private void textBox1_TextChanged(object sender, EventArgs e) 
    { 
     var searchValue = textBox1.Text.Trim();//you can add a ToUpper(); 
     var qry = (from p in dc.Products 
        where p.ProductName.StartsWith(searchValue);//you can add a ToUpper() to p.ProductName 
        select p).ToList(); 
     productDataGridView.DataSource = qry; 
    } 
+0

就是這樣很多謝謝Raphaël – 2012-07-27 14:13:43

+1

@AlphaBird,順便說一下,我認爲你的代碼只能用'Substring(0,aa)' – 2012-07-27 14:15:10

+0

是的,它試圖用Substring(0,aa),它的工作原理,謝謝。 – 2012-07-31 15:31:48

0

從來沒有和我說從不使用==比較2個字符串 總是使用equals()或contains() 如果比較2個字符串,那麼儘管2個字符串看起來完全相同,但很可能會得到錯誤事件。 區別在於每個字符串指向不同的對象。基本上每次你做一個字符串,它會創建一個類String的新對象。

+0

你能舉個例子用equals()使用我最初的問題,我已經嘗試過了,填充文本框時datagrid返回空。 – 2012-07-27 14:18:31

+0

這在java中只有這樣。 http://stackoverflow.com/questions/1659097/c-string-equals-vs – Fr33dan 2012-07-27 14:21:26

+0

以及我切換短到C#從Java。我從來沒有在c#中測試過這個理論。該鏈接證明了我的觀點,我立場糾正;) – 2012-07-27 14:52:17

相關問題