如何删除datagrid中的所有SQL行?

时间:2018-12-25 07:43:39

标签: vb.net

我有datagridview和文本框。我键入项目代码,然后从SQL搜索,然后在datagridview中输入数据。现在,如何从SQL中删除按项目代码在datagridview中的所有项目。

1 个答案:

答案 0 :(得分:0)

这里是一个示例,您可以下载完整的项目here。请注意,项目中有一个脚本来生成代码示例中使用的表。

在此示例中,下面显示的是代码的一部分。表单加载事件将DataTable加载到BindingSource,并且BindingSource成为DataGridView的DataSource。

删除操作,首先检查用户是否输入了帐号,然后检查该帐号是否在DataGridView中(如果这是具有另一个SQL SELECT的多用户环境,则最好检查基础数据库表)声明)。如果找到该帐户,请询问他们是否真的要删除“问题”对话框默认为“否”而不是“是”的记录。如果通过按是进行确认,则运行DELETE语句,如果删除了一条记录,则返回true,否则返回false。

如果操作成功,返回表格,使用BindingSource中的查找从DataGridView中删除记录。

注意事项: 这可以全部以表单完成,但是最好将数据操作与一般的表单操作分开,并使代码以其他形式可用,并且如果数据类在类项目中,则可以在其他项目中使用。

如上所述,如果是多用户环境,则可能要检查要从数据库中删除的记录,而不是当前查看的数据。

(可选)提供一个自动完成的TextBox或ComboBox,其中填充了现有的帐号。这有助于避免用户的猜测。

(可选)从按钮单击事件中提供一种方法来删除当前记录。

表单代码,其中包含DataGridView,TextBox和Button。

Public Class Form1
    Private peopleBindingSource As New BindingSource
    Private operations as New Operations
    Private Sub accountDeleteButton_Click(sender As Object, e As EventArgs) _
        Handles accountDeleteButton.Click

        If Not String.IsNullOrWhiteSpace(accountNumberTextBox.Text) Then

            Dim result = CType(peopleBindingSource.DataSource, DataTable).
                    AsEnumerable().
                    FirstOrDefault(Function(row) row.Field(Of String)("Account") = accountNumberTextBox.Text)

            If result Is Nothing Then
                MessageBox.Show("Failed to find account in the current loaded data.")
                Exit Sub
            End If

            If My.Dialogs.Question($"Remove account '{accountNumberTextBox.Text}'") Then
                If operations.RemoveByAccountNumber(accountNumberTextBox.Text) Then
                    peopleBindingSource.RemoveAt(peopleBindingSource.Find("Account", accountNumberTextBox.Text))
                Else
                    If Not operations.IsSuccessFul Then
                        MessageBox.Show($"Encounter errors{Environment.NewLine}{operations.LastExceptionMessage}")
                    End If
                End If
            End If
        End If

    End Sub
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        peopleBindingSource.DataSource = operations.Read
        If operations.IsSuccessFul Then
            DataGridView1.DataSource = peopleBindingSource
        Else
            accountDeleteButton.Enabled = False
            MessageBox.Show($"Encounter errors{Environment.NewLine}{operations.LastExceptionMessage}")
        End If
    End Sub
End Class

数据类

Imports System.Data.SqlClient
Public Class Operations
    Inherits BaseSqlServerConnection

    Public Sub New()
        DefaultCatalog = "DeleteExample"
    End Sub
    Public Function Read() As DataTable
        Dim dt As New DataTable
        mHasException = False
        Dim selectStatement = "SELECT id,FirstName,LastName,Account FROM dbo.Person"
        Using cn = New SqlConnection() With {.ConnectionString = ConnectionString}
            Using cmd = New SqlCommand() With {.Connection = cn, .CommandText = selectStatement}

                Try
                    cn.Open()
                    dt.Load(cmd.ExecuteReader())
                    dt.Columns("id").ColumnMapping = MappingType.Hidden
                Catch ex As Exception
                    mHasException = True
                    mLastException = ex
                End Try

            End Using
        End Using

        Return dt

    End Function
    ''' <summary>
    ''' Remove account if found and return true
    ''' Account not found, return false
    ''' Error throw, return false
    ''' </summary>
    ''' <param name="accountNumber"></param>
    ''' <returns></returns>
    Public Function RemoveByAccountNumber(accountNumber As String) As Boolean

        mHasException = False
        Dim deleteStatement = "DELETE FROM dbo.Person WHERE Account = @AccountNumber"
        Using cn = New SqlConnection() With {.ConnectionString = ConnectionString}
            Using cmd = New SqlCommand() With {.Connection = cn, .CommandText = deleteStatement}
                cmd.Parameters.AddWithValue("@AccountNumber", accountNumber)
                Try
                    cn.Open()
                    Return cmd.ExecuteNonQuery() = 1
                Catch ex As Exception
                    mHasException = True
                    mLastException = ex
                    Return False
                End Try

            End Using
        End Using

    End Function

End Class