2015-10-21 22 views
-1

如何做搜索,即使它並不確切,但會在DataGridViewC#(搜索按鈕)有一個函數包含

Datagridview

Database

  OleDbCommand cmdDatabase = new OleDbCommand("Select User_ID, Firstname, Lastname, Pass, Account_Type from Account where Lastname'"+textBox1.Text+"'", con); 
      try 
      { 

       OleDbDataAdapter sda = new OleDbDataAdapter(); 

       sda.SelectCommand = cmdDatabase; 
       DataTable dbdataset = new DataTable(); 
       sda.Fill(dbdataset); 
       BindingSource bSource = new BindingSource(); 

       bSource.DataSource = dbdataset; 
       dataGridView1.DataSource = bSource; 
       sda.Update(dbdataset); 

      } 

      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
顯示

回答

0

您可以在SQL語句中使用LIKE,%表示文本之前或之後的任何值,因此%在文本接受「asdsad cavite」之前以及%t之後的%他的文本會接受「cavite dagma」 - 兩者一起接受兩者(「asd CAVITE asd」)。

更喜歡:SQL LIKE Operator

OleDbCommand cmdDatabase = new OleDbCommand("SELECT User_ID, Firstname, Lastname, Pass, Account_Type FROM Account WHERE Lastname LIKE %'"+textBox1.Text+"%'", con); 
      try 
      { 

       OleDbDataAdapter sda = new OleDbDataAdapter(); 

       sda.SelectCommand = cmdDatabase; 
       DataTable dbdataset = new DataTable(); 
       sda.Fill(dbdataset); 
       BindingSource bSource = new BindingSource(); 

       bSource.DataSource = dbdataset; 
       dataGridView1.DataSource = bSource; 
       sda.Update(dbdataset); 

      } 

      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
0

我不知道,如果我有你的權利,但如果你想有一個「包含」像搜索,您可以使用

OleDbCommand cmdDatabase = new OleDbCommand("Select User_ID, Firstname, Lastname, Pass, Account_Type from Account where Lastname LIKE '%"+textBox1.Text+"%'", con); 

關鍵字是Wildcards

您的SQL語句提供了可能的sql注入方式

+0

Your code worked to me!謝謝btw – Rence

+0

抱歉代碼,即時通訊困惑做參數 – Rence

0

也許是這樣的:

 using(OleDbConnection conn = new OleDbConnection(connString)) 
{ 
     conn.Open(); 
     using(OleDbCommand cmd = new OleDbCommand()){ 
     DataTable table = null; 
     cmd.Connection = conn; 

table = new DataTable(); 
      cmd.CommandText = String.Format("SELECT SifraPacijenta, Ime, Prezime, DatumRodjenja, Adresa, Telefon FROM Pacijenti WHERE Ime + ' ' + Prezime LIKE '%{0}%' ORDER BY SifraPacijenta", tbPretragaImePrezime.Text); 
      da = new OleDbDataAdapter(cmd); 
      da.Fill(table); 
} 
} 
      conn.Close(); 
      gridPacijenti.DataSource = table;