2017-10-05 63 views
0

我想知道如何使用列表视图和按钮从数据库中的表中删除一行。使用列表视图从数据库中的表中删除行

我的代码

private void deleteitems() 
{ 
    //DELETE FROM Tbl_Cashier WHERE RecpieId = @RecpieId AND IngredientId = @IngredientId 
    string query = "delete from Tbl_Cashier where Cashier_ID = '" + listView1.SelectedIndices+"' "; 

    using (SqlConnection connection = new SqlConnection(connectionString1)) 
    using (SqlCommand command = new SqlCommand(query, connection)) 
    { 
     connection.Open(); 
     command.Parameters.Remove(listView1.SelectedIndices); 

     command.ExecuteNonQuery(); 
     connection.Close(); 
    } 

    MessageBox.Show("You will see the new data with your next restart of the application", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Information); 
} 

我收到此错误:

An unhandled exception of type 'System.InvalidCastException' occurred in System.Data.dll

Additional information: The SqlParameterCollection only accepts non-null SqlParameter type objects, not SelectedIndexCollection objects.

回答

0

当你提到“一个行”,我们可以假设,如果您只是想从数据库表中删除一行。

另一个重要的假设是您的listview的第一列包含数据库表的Cashier_ID。

因此,这里就是你需要做的:

private void DeleteSelectedItemFromListView() { 

     var cashierId = listView1.FocusedItem.Text; 

     string query = "delete from Tbl_Cashier where [email protected];"; 

     using (SqlConnection con = new SqlConnection(connectionString1)) { 

      try { 

       con.Open(); 

       using (SqlTransaction trans = con.BeginTransaction()) { 

        using (SqlCommand com = new SqlCommand(query, con, trans)) { 

         com.Parameters.AddWithValue("id", cashierId); 

         var should_be_one = com.ExecuteNonQuery(); 

         if (should_be_one == 1) { 

          trans.Commit(); 

         } else { 

          trans.Rollback(); 

          throw new Exception("An attempt to delete multiple rows was detected"); 
         } 

        } 

       } 


      } catch (Exception ex) { 
       MessageBox.Show(ex.Message); 
      } finally { 
       con.Close(); 
      } 

     } 

    } 

但是,如果你想删除从您的ListView(多项选择)几个项目,这是一个不同的故事。

0

您应该删除这一行:
command.Parameters.Remove(listView1.SelectedIndicies)

的话你需要遍历所有的选择,indicies和为每个选定的项目启动查询,如下所示:

private void deleteitems() 
{  
    using (SqlConnection connection = new SqlConnection(connectionString1)) 
    { 
     connection.Open(); 
     foreach(var index in listView1.SelectedIndicies) 
     { 
      // Modify this to get the 'cashier_id' from you listView at the specified row index... 
      // You should also consider using a prepared query... 
      string query = "delete from Tbl_Cashier where Cashier_ID = '" + index +"' "; 
      using (SqlCommand command = new SqlCommand(query, connection)) 
      { 
       // consider checking the return value here if the delete command was successful 
       command.ExecuteNonQuery(); 
      } 
     } 
    } 
    MessageBox.Show("You will see the new data with your next restart of the application", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Information); 
} 

** 没有测试 **

相关问题