2014-03-24 42 views
0

我想在TextBox自動搜索。當我搜索字符串在DataGridView中自動搜索

此代碼運行,但是當我搜索一個整數,這是錯誤:

Cannot perform 'Like' operation on System.Int32 and System.String

我希望你能幫忙,因爲我現在需要它。

private void textBox1_TextChanged(object sender, EventArgs e) 
{ 
    DataView DV = new DataView(dataTable); 
    DV.RowFilter = string.Format("OrderNo LIKE '%{0}%'",textBox1.Text); 
    dataGridView1.DataSource = DV; 
} 

回答

0

您不能使用LIKE運算符來比較數字。我假設你要找到匹配的訂單ID:

DV.RowFilter = string.Format("OrderNo = {0}", textBox1.Text); 

您可能還需要使用int.TryParse()測試在TextBox第一的價值。

private void textBox1_TextChanged(object sender, EventArgs e) 
{ 
    int orderId; 
    if (!int.TryParse(textBox1.Text, out orderId)) 
     return; // not a valid number 

    DataView DV = new DataView(dataTable); 
    DV.RowFilter = string.Format("OrderNo = {0}", orderId); 
    dataGridView1.DataSource = DV; 
} 

如果你真的想訂單ID比較字符串,則必須先將其轉換:

DV.RowFilter 
    = string.Format("CONVERT(column3, System.String) LIKE '%{0}%'", textBox1.Text); 
+0

謝謝你幫它幫助,但如果我不是輸入任何數字我的DataGridView將不顯示任何數據.. – jao

+0

@jao我更新了我的答案。最後的代碼片段應該適合你。 –