2009-06-24 54 views
1

我正在創建一個應用程序,其中我想根據用戶在文本框中輸入的值在DataGridView中顯示行。根據條件從DataBase爲DataGridView填充值

例如, 如果用戶在文本框中輸入書名,則應在DataGridView中顯示關於該書的所有詳細信息。

我已經使用了以下值編碼:

  SqlConnection objSqlConnection = new SqlConnection(); 
      string connectionStringSettings = "Data Source =.; Initial Catalog = LibrarySystemManagement;Integrated Security = SSPI"; 
      private void btnSearch_Click(object sender, EventArgs e) 
      try 
      { 
       objSqlConnection.ConnectionString = connectionStringSettings; 
       objSqlConnection.Open(); 

       if ((txtBookName.Text != "") || (txtCategory.Text != "")) 
       { 

        SqlDataAdapter objSqlDataAdapter = new SqlDataAdapter("select * from LIBRARYBOOKDETAILS where Title = '"+txtTitle.Text+"'", objSqlConnection); 
        SqlCommandBuilder objSqlCommandBuilder = new SqlCommandBuilder(objSqlDataAdapter); 
        DataTable objDataTable = new DataTable(); 
        objSqlDataAdapter.Fill(objDataTable); 
        BindingSource objBindingSource = new BindingSource(); 
        objBindingSource.DataSource = objDataTable; 
        dataGridView1.DataSource = objBindingSource; 
        objSqlDataAdapter.Update(objDataTable); 
        objSqlConnection.Close(); 
       } 
      } 
      catch (Exception e1) 
      { 
       MessageBox.Show(e1.Message + e1.Source); 
      } 

但上面的代碼顯示在表格中輸入的所有行。我的意思是行不是根據條件而改變的。

任何人都可以幫助我找到正確的代碼片段用於檢索基於條件的數據集?

請幫幫我。

在此先感謝。

回答

3

通過直接接受用戶輸入,您可以開放自己的SQL注入,儘管這是一個側面問題。你爲什麼在這一節叫objSqlDataAdapter.Update(objDataTable);

雖然一切看起來不錯我會嘗試兩兩件事:

  1. 取出objSqlDataAdapter.Update(objDataTable);呼叫 - 什麼也沒有修改,那麼,什麼是更新?此時你應該只選擇數據。當它更新時,它也修改表,並且該表充當您的BindingSource的數據源。

  2. 更改選擇命令使用參數,看看這是否有所不同。此步驟具有防止SQL注入的額外好處。

所以更改此設置:

SqlDataAdapter objSqlDataAdapter = new SqlDataAdapter("select * from LIBRARYBOOKDETAILS where Title = '"+txtTitle.Text+"'", objSqlConnection); 

要這樣:

SqlCommand command = new SqlCommand("select * from LIBRARYBOOKDETAILS where Title = @Title", objSqlConnection); 
command.Parameters.AddWithValue("@Title", txtTitle.Text); 

SqlDataAdapter objSqlDataAdapter = new SqlDataAdapter(command);