2017-03-20 6 views
0

今、私は "名前"を選択してテキストを入力するコンボボックスを持っています。私は自分のデータベースからクエリデータを持っています。しかし、今私はどのようにdatagridviewにデータをロードするのか分からない。 これは私のコードボタンの検索です:検索データをコンボボックスとテキストボックスから取得します。 executenotquery()後にデータグリッドビューにデータをロードする方法

private void btnSearch_Click(object sender, EventArgs e) 
     { 
      String strSearch = txtSearch.Text.Trim(); 
      String Selected = cbSearch.GetItemText(cbSearch.SelectedItem); 
      switch (Selected) 
      { 
       case "All Search": 
        LoadData(); 
        break; 
       case "Name": 
        try 
        { 
         if (conn.State == ConnectionState.Open) 
          conn.Close(); 
         MySqlCommand cmd = new MySqlCommand("Select * FROM sinhvien where name LIKE @name"); 
         cmd.Connection = conn; 
         cmd.Connection.Open(); 
         cmd.Parameters.Add(new MySqlParameter("@name", "%" + txtSearch.Text + "%")); 
         cmd.ExecuteNonQuery();***//I dont't know what to do after query here*** 
         MessageBox.Show("Delete this row successfully!\n", 
          "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information); 
        } 
        catch (MySqlException) 
        { 
         MessageBox.Show("Error load data from database!","Notification", MessageBoxButtons.OK, 
          MessageBoxIcon.Error); 
        } 
        break; 
        break; 
      } 
     } 

、その後のDataGridViewにデータベースからデータをロードする方法:

private void LoadData() 
     { 
      try 
      { 
       conn = new MySqlConnection(connString); 
       if (conn.State == ConnectionState.Open) 
        conn.Close(); 
       daSinhVien = new MySqlDataAdapter("SELECT * FROM sinhvien", conn); 
       dtSinhVien = new DataTable(); 
       dtSinhVien.Clear(); 
       daSinhVien.Fill(dtSinhVien); 
       dgvSinhVien.DataSource = dtSinhVien; 
      } 
      catch (MySqlException) 
      { 
       MessageBox.Show("Can't not load data from sinhvien!!","Notification",MessageBoxButtons.OK, 
        MessageBoxIcon.Error); 
      } 
      cbSearch.Items.Add("All Search"); 
      cbSearch.Items.Add("Name"); 
      cbSearch.Items.Add("Age"); 
      cbSearch.Items.Add("Class"); 
      cbSearch.Items.Add("Address"); 
     } 

答えて

0

は、なぜあなたは(cmd.ExecuteNonQueryを使用しています);?

これは、一部のレコードを調整するコマンドのように、データが返ってくるとは思わない文を実行するためのものです。

代わりに、あなたが何かを探している可能性があります:https://msdn.microsoft.com/en-us/library/fksx3b4f.aspx

SqlConnection sqlConnection1 = new SqlConnection("Your Connection String"); 
SqlCommand cmd = new SqlCommand(); 
SqlDataReader reader; 

cmd.CommandText = "SELECT * FROM Customers"; 
cmd.CommandType = CommandType.Text; 
cmd.Connection = sqlConnection1; 

sqlConnection1.Open(); 

reader = cmd.ExecuteReader(); 
// Data is accessible through the DataReader object here. 

sqlConnection1.Close(); 

...これは、MSDNのページオフになっています

関連する問題