7
Answers

Trying to delete entire row from dataGridView and SQLite db.

Ask a question
Stan Sypek

Stan Sypek

9y
2.5k
1
I have a SQLite database that loads in a form.  I can delete data from the dataGridView no problem.  I can also delete it from the table, but only if I select a cell in the table.  I can't figure out how to remove it from the table by selecting the entire row.  The code I am using:
 
Code to load the table:
 

private void readAllRecords()
        {
            try
            {
                var datatable = new DataTable();
                myConnection.Open();
                string commandText = "Select * From Albums";
                SQLiteDataAdapter mySqliteDataAdapter = new SQLiteDataAdapter(commandText, myConnection);
                mySqliteDataAdapter.Fill(datatable);
                myConnection.Close();
                dataGridView.DataSource = datatable;
            }

            catch (Exception)
            {
                throw;
            }
        }
 
 
Code to delete:
 
private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                myConnection.Open();
                SQLiteCommand myCommand = new SQLiteCommand(myConnection);
                myCommand.CommandText = "Delete FROM Albums WHERE AlbumName = '" + this.txtAlbumTitle.Text + "' ";

                 //Must click in AlbumTitle cell per above line to get delete to work 

                myCommand.ExecuteNonQuery();
                myConnection.Close();
                //MessageBox.Show("Your record has been deleted.");
                txtArtistName.Text = "     Artist Name";
                txtAlbumTitle.Text = "     Album Title";
                txtYear.Text = " Year";
                cmbxGenre.Text = "     Genre";
                cmbxMedium.Text = "     Medium";
                btnSave.Enabled = false;
                readAllRecords();
            }

            catch (Exception)
            {

                throw;
            }
        }
 
When I use:
 
foreach (DataGridViewRow row in dataGridView.SelectedRows)
    {
        if (!row.IsNewRow)
        dataGridView.Rows.Remove(row);
    }
 
This removes the selected row from the dataGridView, but does not remove it from the database.
 
Can someone show me how to combine this so I can highlight a row (or multiple rows) in the dataGridView and remove them from the database?  TIA
 
Stan

 

 

 

 


Answers (7)