简体   繁体   English

如何从C#中的其他表单中删除带有查询的列表项?

[英]How to delete a list item with an query from a different form in c#?

I try to delete a list item from my list 'Ship' which is in my database. 我尝试从数据库中的“船”列表中删除一个列表项。 I use 2 classes to split apart my SQL queries (ShipDB.cs for my queries, Ship for my Ship properties). 我使用2个类来拆分SQL查询(ShipDB.cs用于查询,Ship用于Ship属性)。 I want to use the delete button in my form to delete the selected row in my database. 我想使用表单中的删除按钮删除数据库中的选定行。 The button doesn't delete the row and no error mention has been given when clicking the delete button. 该按钮不会删除该行,并且在单击“删除”按钮时未给出任何错误提示。

Here in the ShipDb.cs: 在ShipDb.cs中:

public void Delete()
        {
            using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString))
            {

                connection.Open();
                Ship ship = new Ship();
                SqlCommand commandDelete = new SqlCommand("DELETE FROM Ship WHERE id = " + ship.Id, connection);
                commandDelete.ExecuteNonQuery();
            }
        }

Here in the Form1.cs: 在Form1.cs中:

private void Button3_Click(object sender, EventArgs e)
        {   

             using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString))
                {


                if (dataGridViewShips.SelectedRows.Count == 1)
                {

                    Ship ship = (Ship)dataGridViewShips.SelectedRows[0].DataBoundItem;
                    db.Delete();
                    dataGridViewShips.DataSource = db.GetAll();

                }
            }

        }

I use the db.GetAll to update the database 我使用db.GetAll更新数据库

As Sami said, you aren't telling it what needs deleted. 正如Sami所说,您没有告诉它需要删除哪些内容。

public void Delete(Ship ship)
{
    using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString))
    {
        connection.Open();
        SqlCommand commandDelete = new SqlCommand("DELETE FROM Ship WHERE id = " + ship.Id, connection);
        commandDelete.ExecuteNonQuery();
     }
}
private void Button3_Click(object sender, EventArgs e)
{   
    using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString))
    {
        if (dataGridViewShips.SelectedRows.Count == 1)
        {
            Ship ship = (Ship)dataGridViewShips.SelectedRows[0].DataBoundItem;
            db.Delete(ship);
            dataGridViewShips.DataSource = db.GetAll();
        }
    }
}

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

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