Search code examples
c#winformsdatagridviewlocal-database

How can i delete data from a datagridview c#?


When i use the code below,it does delete a row from a datagridview but when i refresh the page it does not..

    private void DeleteData_Click(object sender, EventArgs e)
    {

        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Selected)
            {
                dataGridView1.Rows.RemoveAt(row.Index);
                break; 
        }
        using (SqlConnection sqcon = new SqlConnection(@"MY CONNECTION STRING")) 
        {
            SqlCommand Scmd = new SqlCommand();

            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                DataGridViewRow delrow = dataGridView1.Rows[i];
                if (delrow.Selected == true)
                {
                    dataGridView1.Rows.RemoveAt(i);
                    try
                    {
                        Scmd.CommandText = "DELETE FROM Technican WHERE ID=" + (i++) + "";
                        sqcon.Open(); //ADDED
                        int count = Scmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
            }
        }

    }

What should i use to delete row from both local database and datagridview?


Solution

  • i think the connection not be assigned to the command object.

    SqlCommand Scmd = new SqlCommand();
    Scmd.Connection = sqcon;
    

    also i preferred to use DataGridView.SelectedRows instead of looping all records in grid.

    full code

        private void DeleteData_Click(object sender, EventArgs e)
        {
            var rowsToDelete = dataGridView1.SelectedRows;
            using (SqlConnection sqcon = new SqlConnection(@"MY CONNECTION STRING"))
            {
                SqlCommand Scmd = new SqlCommand();
                Scmd.Connection = sqcon;
                sqcon.Open(); //ADDED   
                foreach (DataGridViewRow row in rowsToDelete)
                {
                    try
                    {
                        Scmd.CommandText = "DELETE FROM Technican WHERE ID=" + row.Cells["Id"].Value.ToString() + "";
                        int count = Scmd.ExecuteNonQuery();
    
                        dataGridView1.Rows.Remove(row);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
    
                }
                sqcon.Close();
            }
        }