【问题标题】:C# Deleting Rows from DataGridView and Updating DatabaseC# 从 DataGridView 中删除行并更新数据库
【发布时间】:2016-03-07 21:16:20
【问题描述】:

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

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

for (int i = 0; i < Products.Rows.Count; i++)
{
    DataGridViewRow dr = Products.Rows[i];
    if (dr.Selected == true)
    {
        Products.Rows.RemoveAt(i); 
    }
}

【问题讨论】:

  • 您需要调用数据库来删除选定的行。
  • 数据库已经存在,应用程序运行时加载。问题是,当通过“删除”按钮删除 1 个或多个选中的行时,这些行会消失,但如果我重新启动程序会再次出现。任何想法如何更新数据库上的这些更改?
  • 你能指定你使用的数据库吗? MS SQL Server 或 MySQL 或 Oracle 等?

标签: c# database datagridview rows


【解决方案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

【讨论】:

    【解决方案2】:

    您必须将必要的调用写给您的数据库管理员。如果您使用的是 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 );
    }
    

    【讨论】:

      【解决方案3】:
      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") 
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多