2014-06-11 32 views
0

我有一个问题,从我的数据库中删除选定的行,事实上,我有一个C#中的窗体,其中包含一个dataGridView连接到数据库和一个按钮“删除”当我点击按钮时,这应该删除dataGridView和数据库中选定行(单元格[0]和单元格[1])的信息。现在,我面临从数据库中删除选定行的问题,这是我的代码:我不能从我的数据库中删除信息

private void button4_Click(object sender, EventArgs e) 
     { 
      if (journalDataGridView.SelectedRows.Count == 1) 
      { 
       DataGridViewRow row = journalDataGridView.SelectedRows[0]; 
       journalDataGridView.Rows.Remove(row); 
       SqlConnection connection = new SqlConnection(connectionString); 
       connection.Open(); 
       SqlCommand sql = new SqlCommand("delete from journal where code_journal='" + journalDataGridView.CurrentRow.Cells[0].Value.ToString() + "'AND intitule='" + journalDataGridView.CurrentRow.Cells[1].Value.ToString() + "';", connection); 
       connection.Close(); 
      } 
} 

DataGridView中包含两列 “code_journal和initule” 感谢的帮助

+0

** initule ** or ** intitule ** ?? –

+0

它是intitule @Andy G :) – Lina

回答

2

除了answer由sorton9999提供,另一个问题是你没有做你的SqlCommand对象什么。

创建后,您需要执行它:

SqlConnection connection = new SqlConnection(connectionString); 
connection.Open(); 
SqlCommand sql = new SqlCommand("delete from journal where code_journal='" + journalDataGridView.CurrentRow.Cells[0].Value.ToString() + "'AND intitule='" + journalDataGridView.CurrentRow.Cells[1].Value.ToString() + "';", connection); 
sql.ExecuteNonQuery(); 
connection.Close(); 

你做字符串连接打开自己最多可能的SQL注入,使用参数化查询来代替。此外,您应该将SqlConnectionSqlCommand包含在using声明中,以确保它们妥善处置。类似这样的:

using (SqlConnection connection = new SqlConnection(connectionString)) 
{ 
    using (SqlCommand sql = new SqlCommand("delete from journal where [email protected] AND [email protected]", connection)) 
    { 
     cmd.Parameters.AddWithValue("@codeJournal", journalDataGridView.CurrentRow.Cells[0].Value.ToString()); 
     cmd.Parameters.AddWithValue("@inituleVal", journalDataGridView.CurrentRow.Cells[1].Value.ToString()); 
     connection.Open(); 
     sql.ExecuteNonQuery(); 
    } 
} 
-1

它可以像EAS y as,你的单引号(')和你的SQL语句中的AND之间没有空格?

值得一试...

+0

感谢sorton9999你的回复,但我仍然有同样的问题行从dataGridView删除,但不是从数据库(我与本地数据库工作) – Lina

+0

感谢你们所有人!我的问题解决了从数据库中删除的信息,但是当我第二次点击显示表时,信息再次出现在dataGridView中(我使用绑定'MainDataSet') – Lina

5

要删除的行,然后引用了错误的行与CurrentRow财产。

您也没有使用参数来避免sql注入。

您还没有执行命令:

DataGridViewRow row = journalDataGridView.SelectedRows[0]; 
connection.Open(); 
using (SqlCommand sql = new SqlCommand("delete from journal where [email protected]", connection)) { 
    sql.Parameters.AddWithValue("@codeJournal", row.Cells[0].Value.ToString()); 
    sql.ExecuteNonQuery(); 
} 
connection.Close(); 
journalDataGridView.Rows.Remove(row); 
相关问题