C#从DataGridView删除行并更新数据库

时间:2016-03-07 11:39:01

标签: c# database datagridview rows

我正在尝试创建一个包含DataGridView的应用程序,其数据绑定到DataSource。我在Form_Load上使用fill方法,我想知道如何删除一个或多个已复选的行,不仅可以从我的表中删除,还可以同时从数据库/数据源中删除。

我在删除按钮上使用此代码,但它不会永久删除所选行。有帮助吗?

var valuetostr = valueofthis.toString();

3 个答案:

答案 0 :(得分:1)

您正在做的是仅从DataGridView删除所选行。

您没有进行任何数据库调用来删除行。

我假设您使用的是Microsoft SQL服务器。

在这种情况下,您需要获得唯一标识产品的东西。例如产品ID。

假设您已将数据库中的ProductId列绑定到DataGridView中的某些列。

您的代码应如下所示。

//string variable to capture product Ids for selected products
System.Text.StringBuilder productIds = new System.Text.StringBuilder(string.empty);

for (int i = 0; i < Products.Rows.Count; i++)
{
    DataGridViewRow dr = Products.Rows[i];

    if (dr.Selected == true)
    {
        Products.Rows.RemoveAt(i);

        productIds.Append(productIds.length > 0 ? "," + Convert.ToString(dr["ProductId"]) : Convert.ToString(dr["ProductId"]));
    }
}

DeleteProducts(productIds.ToString());

现在,您的DeleteProducts方法应如下所示。

private int DeleteProducts(string productIds)
{
    int recordsDeleted = 0;

    using (SqlConnection conn = new SqlConnection("Your connection string here"))
    {
        try
        {
            using (SqlCommand cmd = new SqlCommand("Your SQL Stored Procedure name here", conn))
            {
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter paramProductIds = new SqlParameter("@productIds", varchar(2000));
                paramProductIds.Value = productIds;

                cmd.Parameters.Add(paramProductIds);

                conn.Open();

                recordsDeleted = cmd.ExecuteNonQuery();
            }
        }
        finally { conn.Close(); }

    }

    return recordsDeleted;
}

您的存储过程应如下所示(假设MS SQL Server)。

CREATE PROCEDURE DeleteProducts
    @productIds VARCHAR(2000)
AS
BEGIN
    DELETE FROM Products WHERE ProductId IN (SELECT item FROM dbo.Split(',', @productIds))
END

答案 1 :(得分:0)

您必须向数据库管理员写入必要的调用。如果您正在使用MYSQL,那么您可以使用:

for (int i = 0; i < Products.Rows.Count; i++)
{
    DataGridViewRow dr = Products.Rows[i];
    if (dr.Selected == true)
    {
        Products.Rows.RemoveAt(i);
        // CODE ADDED
        MySqlCommand cmd = sql.CreateCommand(); // creates the MySQL object needed for queries (I think there's another way also, but I use this)
        cmd.CommandText = "DELETE FROM table WHERE id = 1"; // sets the query

        try
        {
            cmd.ExecuteNonQuery(); // executes the query
        }
        catch( MySqlException e )
        {
            sql.Close();
            Console.WriteLine( e.Message );
        }
        sql.Close();
        // CODE ADDED
    }
}

sql之前被定义为MySqlConnection sql,它的初始化是:

try {
    sql = new MySqlConnection( {SQL_CONNECTION_STRING} );
    try
    {
        sql.Open();
        sql.Close(); // Close the DB. This block is useful to check whether or not the connection was successfully opened
    }
    catch ( MySqlException e )
    {
        Console.WriteLine( e.Message );
    }
}
catch ( MySqlException e )
{
    Console.Write( e.Message );
}

答案 2 :(得分:0)

if (MessageBox.Show("Confirm ?","DELETE", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
    string name = dataGridView1.Rows[e.RowIndex].Cells[WHEREINDEX].Value.ToString();
    sql = "DELETE FROM [TABLE] WHERE [id] = " + dataGridView1.Rows[e.RowIndex].Cells[WHEREINDEX].Value.ToString();

    if (db.Exec(sql) > 0)
    {
        MessageBox.Show(name + " deleted");
        dtSummary.Rows.Find(dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString()).Delete();
        dataGridView1.Refresh();
    }
    else 
    {
        MessageBox.Show("error while deleting") 
    }
}