2016-08-18 57 views
-2

我一直在处理这段代码几个小时,现在它显示的信息框已被成功删除,但它不会删除数据库我似乎无法找到我出错的地方。从数据库中删除选定的行数据

private void simpleButton5_Click(object sender, EventArgs e) 
    { 
     for (int i = 0; i < dataGridView1.Rows.Count; i++) 
     { 
      DataGridViewRow delrow = dataGridView1.Rows[i]; 
      if (delrow.Selected == true) 
      { 
       //A YesNo enabled messagebox 
       DialogResult dialogResult = DevExpress.XtraEditors.XtraMessageBox.Show("Are you sure you want delete the selected client's information?", " ", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); 
       //An if statement for a yes selected button on the messagebox 
       if (dialogResult == DialogResult.Yes) 
       { 
        dataGridView1.Rows.RemoveAt(i); 
        try 
        { 
         Conn.Open(); 
         SqlCommand Scd = new SqlCommand("Delete From Client WHERE ClientID=" + i + "" ,Conn); 
         Scd.ExecuteNonQuery(); 
         Conn.Close(); 
         DevExpress.XtraEditors.XtraMessageBox.Show("You have successfully deleted the selected client's information on the system", " ", MessageBoxButtons.OK, MessageBoxIcon.Information); 
        } 
        catch (Exception ex) 
        { 
         DevExpress.XtraEditors.XtraMessageBox.Show(ex.ToString()); 
        } 
        } 
       //An if statement for a no selected button on the messagebox 
       else if (dialogResult == DialogResult.No) 
       { 
        //Closing this form and opening the main menu form 
        this.Hide(); 
        MainMenu mm = new MainMenu(); 
        mm.ShowDialog(); 
        this.Close(); 
        this.Dispose(); 
       } 
      } 
     } 
    } 
+0

您已经将您提供给用户的数据视图与实际数据混合在一起。一个DataAdapter可以让你摆脱所有的代码:'myDA.Update(myDT);' – Plutonix

回答

4

ClientID很可能不是i(这只是行索引)。从行数据中获取真实的客户端ID。

int clientID = (int)dataGridView1.Rows[i].Cells[indexOfClientIDColumn].Value; 
SqlCommand Scd = 
    new SqlCommand("Delete From Client WHERE ClientID=" + clientID , Conn); 

或按名称获取

int clientID = (int)dataGridView1.Rows[i].Cells["ClientID"].Value; 

右列,也更好地利用command parameters

+0

非常感谢你 – TheBells

5
"Delete From Client WHERE ClientID=" + i + "" 

您删除与客户端ID = i一行。但等待什么i?它是你的for循环中的临时变量。因此,除非您的数据网格视图包含数据库中的所有行,并且ID以1开头,并且每次您将删除其他客户端的数据时,ID都会加1。

您可能会做类似WHERE ClientID=" + delrow["ClientID"]或其他您可以获得实际ID的方式。

但作为一个方面说明。帮你一个忙,并使用Parameterized Sql来防止sql注入。

2

根据你的循环,你的变量i的rowIndex,它总是会为0,1,2,3,4 ... N

IMO,我不认为你得到了客户端ID与您的客户表中的值。你可以仔细检查一下你是否拥有和那些相同的键值。

你需要从你的“的DataGridViewRow”

2

我相信得到的客户端ID后面的错误是在这里:

SqlCommand Scd = new SqlCommand("Delete From Client WHERE ClientID=" + i + "" ,Conn);

你传入的客户端ID DataGrid的线,而不是真实ID。

+0

好吧,我明白,任何建议,我怎么可以实际修复代码 – TheBells