delete child rows when deleting parent row datagridview

mond007

Active member
Joined
Apr 26, 2010
Messages
37
Location
near Solihull, Birmingham UK
Programming Experience
10+
I have had a look in a number of areas but can not seem to work out the code to delete child rows when deleting the parent. See

VB.NET:
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
    '------------------------
    '     DELETE PARENT ROW CODE                'MsgBox("Clicked Column is " & e.ColumnIndex)
    '------------------------
    If e.ColumnIndex <> 7 Then                  
        Exit Sub
    End If
    Dim DeleteQuestionNo As String = DataGridView1.Rows(e.RowIndex).Cells(1).Value

    If e.RowIndex <> -1 Then
        If DialogResult.Yes = MessageBox.Show("Please confirm you wish to delete Question No " & DeleteQuestionNo & " ?", "Delete Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) Then
            DataGridView1.Rows.RemoveAt(e.RowIndex)
            ' -------------------------------------
            ' NOW DELETE ASSOCIATED CHILD ROWS
            '--------------------------------------
            MsgBox("Selected Parent Row is " & DeleteQuestionNo)
            Dim foundParentRow As DataRow = CareTrainQuestionAnswerData.Tables("Questions").Select(String.Format("QuestionNo ='{0}'", DeleteQuestionNo)).FirstOrDefault
            If Not foundParentRow Is Nothing Then
                Dim childRows As List(Of DataRow) = foundParentRow.GetChildRows("Questions_To_Answers").ToList
                For Each childRow In childRows
                        MsgBox("Associated Child Rows are : " & UCase(childRow("AnswerRef").ToString) & " " & childRow("AnswerDescription").ToString)
                    DataGridView1.Rows.RemoveAt(e.RowIndex)
                Next
                DataGridView1.Refresh()
            End If
        End If
    End If
End Sub

Could it be that I have deleted the parent before the child records ? Any help would be appreciated ?

Thanks Kuldip.
 
If you're working with DataRows then why isn't your grid bound? You're making something that should be very easy much harder. If you have a DataSet with two DataTables and a DataRelation between them, you can configure the relation to cascade deletes. You then simply call the Delete method of the parent DataRow, either explicitly or one of several implicit ways, and the child records are deleted automatically, without any code at all.
 
Back
Top