从datagridview中删除记录

时间:2014-01-18 13:32:52

标签: vb.net datagridview

在VB2012中,我创建了一个以SQL2012作为后端的学生管理软件。以下代码用于在单击DELETE按钮时从datagridview中删除所选记录:

 Private Sub Delete_Click(sender As Object, e As EventArgs) Handles Delete.Click
        Dim DelStudent As StudentDataSet1._masterRow
        DelStudent= CType(CType(StudentmasterBindingSource.Current, DataRowView).Row, StudentDataSet1.Student_masterRow)
        DelStudent.Delete()
        Me.Validate()
        Me.StudentmasterBindingSource.EndEdit()
        Me.Student_masterTableAdapter.Update(StudentDataSet1.Student_master)
End Sub

但是,不删除所选行,而是删除第一行。请帮忙......

2 个答案:

答案 0 :(得分:0)

从绑定源的角度来看,所选行不是必需的。您需要使用DataGridView.SelectedRows。每个都是DataGridViewRow,您应该能够检索DataGridViewRow.DataBoundItem,将其投放到DataRow,然后使用Delete

答案 1 :(得分:0)

以下代码也很有帮助

 Private Sub btnRemoveItem_Click(sender As Object, e As EventArgs) Handles btnRemoveItem.Click
        If datagridviewname.SelectedRows.Count > 0 Then
            For i As Integer = datagridviewname.SelectedRows.Count - 1 To 0 Step -1
                datagridviewname.Rows.RemoveAt(datagridviewname.SelectedRows(i).Index)
            Next
        Else
            MessageBox.Show("Select Row to remove")
        End If
    End Sub