从数据库中删除选定的行数据

时间:2016-08-18 18:18:11

标签: c#

我已经在这个代码上工作了几个小时,现在它显示了信息已成功删除的消息框,但它没有删除数据库,我似乎无法找到我出错的地方。

 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();
                }
            }
        }
     }

4 个答案:

答案 0 :(得分:5)

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

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

您可能会执行WHERE ClientID=" + delrow["ClientID"]之类的操作或以其他方式获取实际ID。

但作为旁注。帮自己一个忙,并使用Parameterized Sql来阻止sql注入。

答案 1 :(得分: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

答案 2 :(得分:2)

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

IMO,我不认为您在Client表中获得了具有这些值的ClientID。你能仔细检查一下你的键值是否与那些相同。

您需要从&#34; DataGridViewRow&#34;

获取ClientID

答案 3 :(得分:2)

我相信错误在这里:

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

您将ClientID作为datagrid的行传递,而不是真实ID。

相关问题