Hello. I solve the following problem:
There is an Access database of two related tables (one-to-many relationship; one row of table1 corresponds to several rows of table2). There are two datadds on the form to display both database tables.
It is necessary to implement the function of deleting data from the database (and accordingly from data nodes) that works as follows: when deleting a selected row from the main table (dataGridView1), also delete all its related rows from the second table (dataGridView2).
I compiled this method, but it deletes through a stump-deck, I do not see the logic in its deletions ((What is the cant?

private void buttonDeleteMainTable_Click(object sender, EventArgs e) { if (MessageBox.Show("Удалить запись?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { string str; str = Convert.ToString(dataGridView1.CurrentRow.Cells[0].Value);//захват значения индекса записи из первой таблицы for (int i = 0; i < dataGridView2.RowCount; i++) { if (dataGridView2.Rows[i].Cells[1].Value.ToString() == str) { dataGridView2.Rows[i].Selected = true; nameFirmModelParamBindingSource.RemoveCurrent(); model_ParamTableAdapter.Update(dataBaseMDBDataSet._Model_Param); } } nameFirmBindingSource.RemoveCurrent(); name_FirmTableAdapter.Update(dataBaseMDBDataSet.Name_Firm); } } 
  • one
    Use cascade delete related entries in link properties. When deleting from the table on the "one" side, the records on the "many" side will be deleted without additional gestures themselves ... - Akina

2 answers 2

Question: Have you checked the "cascade deletion of files"? If not, then when recording from the main table in Access itself, the record associated with it is not deleted.
If I understood correctly, you tied one table to one grid, and the second to another.
If this is the case, then it is sufficient in the DataSet, which is connected to both grids, to delete a row from the main table. When deleting, delete and the associated entry in the subordinate.

  • Thanks, I will try - Spectre1146
  • Throws an exception: System.InvalidOperationException: "It doesn’t allow removal of items." - Spectre1146
  • Can I be more specific? How do you delete a line? Which line throws an exception? - Valery Losev

All figured out. Thanks to Valery Losev for the tip.

Here is the code:

 string str; str = Convert.ToString(dataGridView1.CurrentRow.Cells[0].Value);//захват значения индекса строки из первой таблицы for (int i = 0; i < dataGridView1.RowCount; i++) { if (dataGridView1.Rows[i].Cells[0].Value.ToString() == str) { dataBaseMDBDataSet.Name_Firm.Rows[i].Delete(); model_ParamTableAdapter.Update(dataBaseMDBDataSet._Model_Param); name_FirmTableAdapter.Update(dataBaseMDBDataSet.Name_Firm); } }