2013-03-03 89 views
5

我想把一個文本框作爲一個Rowfilter在textchanged事件下!行過濾器中的多個參數

下面的代碼是用來GRID能得到相應的Reg_NumberCustomer_Name這是在文本框中輸入!

笏的令人驚訝的事實是,這個代碼直接將第二個參數

(IE)
((DataTable)radGridView1.DataSource).DefaultView.RowFilter = "Reg_Number like '%" + radTextBoxControl1.Text + "%'";

試圖切換線,但無論我做什麼,它忽略了一日一和採取第二

我試圖把和兩個在一個單一的行,bt不工作,請幫我frnzz!

private void radTextBoxControl1_TextChanged(object sender, EventArgs e) 
{ 
    try 
    { 
     ((DataTable)radGridView1.DataSource).DefaultView.RowFilter = 
      "Customer_Name like '%" + radTextBoxControl1.Text + "%'"; 
     ((DataTable)radGridView1.DataSource).DefaultView.RowFilter = 
      "Reg_Number like '%" + radTextBoxControl1.Text + "%'"; 
    } 
    catch (Exception) { } 
} 

回答

6

這是因爲第二次分配將替換第一個

myDataTable.DefaultView.RowFilter = "firstFilter"; 
myDataTable.DefaultView.RowFilter = "secondFilter"; 
// Now RowFilter is "secondFilter" 

必須與邏輯相結合的2個過濾器或獲得結果滿足兩個條件:

myDataTable.DefaultView.RowFilter = "firstFilter OR secondFilter"; 

var view = ((DataTable)radGridView1.DataSource).DefaultView; 
string escapedText = radTextBoxControl1.Text.Replace("'", "''"); 
view.RowFilter = "Customer_Name LIKE '%" + escapedText + "%' OR " + 
        "Reg_Number LIKE '%" + escapedText + "%'"; 

它成爲與String.Format更加清晰:

view.RowFilter = String.Format("Customer_Name LIKE '%{0}%' OR Reg_Number LIKE '%{0}%'", 
           escapedText); 

或者,因爲C#7.0,用繩子插值:

view.RowFilter = 
    $"Customer_Name LIKE '%{escapedText}%' OR Reg_Number LIKE '%{escapedText}%'"; 

另外,確保由兩個單引號來代替單引號。這使得SQL字符串包含引號,並防止SQL-注射:

SELECT * FROM myTable WHERE Name = 'Andy''s Pub'; 

您必須OR結合這兩個條件,而不是AND是,用戶將進入要麼客戶名稱的原因註冊號碼(我們只有一個文本框)。

或者,您可以檢查條目是否格式化爲註冊號,並應用相應的過濾器。在僞代碼:

if (radTextBoxControl1.Text is formatted as reg_nr) { 
    view.RowFilter = "Reg_Number LIKE '%" + escapedText + "%'"; 
} else { 
    view.RowFilter = "Customer_Name LIKE '%" + escapedText + "%'"; 
} 
+0

哇!這是一個簡短的例子:)非常感謝:) – user2128912 2013-03-24 12:07:42

2

這應該工作:

((DataTable)radGridView1.DataSource).DefaultView.RowFilter = 
    "Customer_Name like '%" + radTextBoxControl1.Text + "%' AND Reg_Number like '%" + radTextBoxControl1.Text + "%'"; 
+0

我試了一下:)謝謝 – user2128912 2013-03-24 12:07:24

1

我認爲你需要或運算,而不是與"Customer_Name like '%" + radTextBoxControl1.Text + "%' OR Reg_Number like '%" + radTextBoxControl1.Text + "%'";

+0

非常感謝你:) – user2128912 2013-03-24 12:07:06