简体   繁体   English

SQL行未删除

[英]SQL rows are not being deleted

So I have this code that is designed to delete a row in mySQL server database judging by what is selected in my list box. 因此,我有这段代码旨在根据在列表框中选择的内容来删除mySQL服务器数据库中的行。 Here is the code I have to remove the rows: 这是我必须删除行的代码:

private void remove_btn_Click(object sender, EventArgs e)
    {
        try
        {
            if (Calls_lsb.SelectedItem == null)

                MessageBox.Show("Please select an item for deletion.");
            }
            else
            {
                int i = Calls_lsb.SelectedIndex;
                if (i > 0)
                {
                    SqlConnection connection = new SqlConnection(//My Connection String);
                    string sqlStatement1 = "DELETE FROM Records WHERE CallID = @Id";
                    string sqlStatement2 = "DELETE FROM Calls WHERE CallID = @Id";

                    connection.Open();
                    SqlCommand cmd1 = new SqlCommand(sqlStatement1, connection);
                    cmd1.Parameters.AddWithValue("@Id", Calls_lsb.Items[i]);
                    cmd1.ExecuteNonQuery();
                    SqlCommand cmd2 = new SqlCommand(sqlStatement2, connection);
                    cmd2.Parameters.AddWithValue("@Id", Calls_lsb.Items[i]);
                    cmd2.ExecuteNonQuery();
                    connection.Close();

                    Calls_lsb.Items.Remove(Calls_lsb.Items[i]);
                }
                else
                {
                }
            }
        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.ToString());
        }
    }

I get no exceptions and I have similar code that adds records that works fine. 我没有例外,并且我有类似的代码可以添加工作正常的记录。 I tried stepping into the code but it all seemed fine. 我尝试进入代码,但一切似乎都很好。 It simply just does not delete the row from the database. 它只是不删除数据库中的行。 It removes the correct item from the list, just not the database. 它从列表中删除正确的项目,而不是从数据库中删除。

If anyone could shine some light on this situation that would be great, thanks! 如果有人能在这种情况下大放异彩,那就太好了,谢谢!

Edit : Ok, I seem to have fixed the problem. 编辑:好的,我似乎已经解决了问题。 I just removed the whole i = selected index stuff and replace the 'Calls_lsb.Items[i]' with '(Calls_lsb.SelectedIndex + 1)'. 我只是删除了整个i =选定的索引内容,并将'Calls_lsb.Items [i]'替换为'(Calls_lsb.SelectedIndex +1)'。 I don't really understand why I was getting an exception when I tried to add 1 to i as this is basically doing the same thing. 我真的不明白为什么在尝试将1加到i时为什么会出现异常,因为这基本上是在做同样的事情。

Replace your below line code. 替换下面的行代码。

  cmd1.Parameters.AddWithValue("@Id", Calls_lsb.Items[i]);
  //with 
  cmd1.Parameters.AddWithValue("@Id", Calls_lsb.Items[i].Value);

and

  cmd2.Parameters.AddWithValue("@Id", Calls_lsb.Items[i]);

// with //与

  cmd2.Parameters.AddWithValue("@Id", Calls_lsb.Items[i].Value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM