【问题标题】:How to delete multiple or all rows in DataGridView? [duplicate]如何删除 DataGridView 中的多行或所有行? [复制]
【发布时间】:2017-08-09 12:10:20
【问题描述】:

我想使用DataGridView 删除数据库中的多行或所有行。 例如。如果我在DataGridView 中有 10 行,则应选择并删除所有 10 行。这是我使用DataGridView删除数据库中单行的代码。

private void btnDeleteProduct_Click(object sender, EventArgs e)
    {
        ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["MyDBConnectionString"];
        string connectionString = conSettings.ConnectionString;

            if (ProductServicesDataGrid.CurrentRow.Selected)
            {
                string selectedCode = ProductServicesDataGrid.CurrentRow.Cells[0].Value.ToString();

                conn = new SqlConnection(connectionString);

                try
                {
                    conn.Open();
                    cmd = new SqlCommand("DELETE FROM ProductServices where ProductCode='" + selectedCode + "' ", conn);
                    sdr = cmd.ExecuteReader();
                    loadProductServicesTable();

                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    conn.Close();
                }
            }
            else
            {
                MessageBox.Show("Row is not Selected");
            }
    }

有人可以帮我修改我的代码吗?

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    首先,您不应该使用CurrentRow 属性,因为它只返回一行。反而。使用SelectedRows 集合并遍历它。

    其次,从不在命令文本中连接参数。相反,请使用参数化查询。

    //connection.Open is moved out of the loop, to avoid unnecessary open/close
    conn = new SqlConnection(connectionString);
    conn.Open();
    
    try
    {
        foreach (var row in ProductServicesDataGrid.SelectedRows)
        {
            string selectedCode = row.Cells[0].Value.ToString();
    
            try
            {
                cmd = new SqlCommand("DELETE FROM ProductServices where ProductCode=@productCode", conn);
                cmd.Parameters.Add(.Parameters.Add("productCode", SqlDbType.VarChar).Value = selectedCode;
                sdr = cmd.ExecuteReader();
                //this probably shouldn't be here, but outside the foreach loop.
                //that way table will be loaded after deletion of those n rows.
                //loadProductServicesTable();
    
    
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        conn.Close();
    }
    
    //refresh products after deletion
    loadProductServicesTable();
    

    【讨论】:

    • 我想建议在循环外打开和关闭连接,否则你不必要地打开和关闭它
    • @MongZhu,这是个好建议。但是,一一删除所有行的想法也很糟糕......
    • 我同意,但我忘记了它是如何构建列表并使用关键字IN.. :D 否则我会写一个答案:)
    • @MongZhu 是啊,我也想到了,不过现在懒得写了……:)
    • @Hamms 阅读了有关 sql injection... 的信息,也必须阅读 xkcd comic
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 2017-08-17
    • 2019-12-28
    • 2012-06-21
    • 2016-11-28
    • 2021-07-30
    相关资源
    最近更新 更多