2017-05-29 85 views
-2

我想從使用3個不同的組合框的數據庫中搜索數據。使用C#進行多重Combobox搜索#

我想單擊搜索按鈕,單擊後我希望數據出現在所有選定的組合框中。

數據應該與我選擇的3個組合框完全相同。所以我該怎麼做?謝謝您的幫助。

現在,我使用如果其他,但我想改變他們,就像我上面說的。

private void btnsubmit_Click(object sender, EventArgs e) 
    { 
     SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\acap\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30"); 
     DataTable ds = new DataTable(); 

     if (comboBox1.Text.Length > 0) 
     { 
      SqlDataAdapter sda = new SqlDataAdapter("SELECT No_ic as [I/C No.], Name as [Name], Program as [Program], No_Matric as [Matric No.], No_HP as [Handphone No.], Address as [Address], State as [State], Kohort as [Kohort] FROM Student where Program LIKE '" + comboBox1.Text + "%' ", con); 
      sda.Fill(ds); 

     } 
     else if (comboBox2.Text.Length > 0) 
     { 

      SqlDataAdapter sda = new SqlDataAdapter("SELECT No_ic as [I/C No.], Name as [Name], Program as [Program], No_Matric as [Matric No.], No_HP as [Handphone No.], Address as [Address], State as [State], Kohort as [Kohort] FROM Student where State LIKE '" + comboBox2.Text + "%' ", con); 
      sda.Fill(ds); 
     } 
     else if (comboBox3.Text.Length > 0) 
     { 
      SqlDataAdapter sda = new SqlDataAdapter("SELECT No_ic as [I/C No.], Name as [Name], Program as [Program], No_Matric as [Matric No.], No_HP as [Handphone No.], Address as [Address], State as [State], Kohort as [Kohort] FROM Student where Kohort LIKE '" + comboBox3.Text + "%' ", con); 
      sda.Fill(ds); 
     } 
+0

你想查詢什麼? – Krishna

+0

我只是編輯我的代碼和上面的問題。 @Krishna –

回答

0

作爲一般的方法,您需要動態組合您選擇的條件。

String query = "SELECT No_ic as [I/C No.], Name as [Name], Program as [Program], No_Matric as [Matric No.], No_HP as [Handphone No.], Address as [Address], State as [State], Kohort as [Kohort] FROM Student"; 
List<String> conditions = new List<String>(); 
if (comboBox1.Text.Length > 0) 
{ 
    conditions.Add("Program LIKE '" + comboBox1.Text + "%' "); 
} 
if (comboBox2.Text.Length > 0) 
{ 
    conditions.Add("State LIKE '" + comboBox2.Text + "%' "); 
} 
if (comboBox3.Text.Length > 0) 
{ 
    conditions.Add("Kohort LIKE '" + comboBox3.Text + "%' "); 
} 

if (conditions.Count > 0) 
{ 
    query = query + " WHERE " + String.Join(" AND ", conditions.ToArray()) 
} 
SqlDataAdapter sda = new SqlDataAdapter(query, con); 
sda.Fill(ds);