2017-05-29 17 views
-2

3つの異なるcomboBoxを使用しているデータベースからデータを検索したいと思います。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); 
関連する問題