SarahF
SarahF

Reputation: 11

C# Deleting Rows from DataGridView and Updating Database

I am trying to create an application that will contain a DataGridView with data bound to a DataSource. I use the fill method on Form_Load and I would like to know how do I delete one or more checkboxed rows, not only from my table but also from the database/datasource at the same time.

I use this code on the delete button, but it doesn't remove permanently the selected rows. Any help?

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

Upvotes: 1

Views: 5418

Answers (3)

KA-Yasso
KA-Yasso

Reputation: 551

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") 
    }
}

Upvotes: 0

Devraj Gadhavi
Devraj Gadhavi

Reputation: 3611

What you are doing is removing the selected rows from the DataGridView only.

You are not making any database call to delete the rows.

I assume you are using Microsoft SQL server.

In that case you will need to get the something that uniquely identifies product. For example Product Id.

Assuming you've got your ProductId column from the database bound to some column in DataGridView.

Your code should be like below.

//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());

Now your DeleteProducts method should be as below.

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;
}

And your stored procedure should be as below (Assuming MS SQL Server).

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

Upvotes: 1

Jistycs
Jistycs

Reputation: 11

You have to write the necessary call to your DB manager. If you're using MYSQL, then you could use:

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 was defined before as MySqlConnection sql, and it's initialization was:

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 );
}

Upvotes: 0

Related Questions