【问题标题】:Need help editing Customer Info in VB.net需要帮助在 VB.net 中编辑客户信息
【发布时间】:2019-07-14 18:00:17
【问题描述】:

我正在尝试使用我的 C# 项目编辑客户,以了解如何在 VB.net 中实现此代码。该项目成功地添加了客户,但在编辑客户时,事情变得有点复杂,因为我需要获取所选行的 id 并将其传递给字符串。我有 MainForm.vb,当我单击“编辑”时可以打开 CustomerForm.vb。当 CustomerForm.vb 打开时,它无法显示客户的信息。我不确定FillDataTable() 函数是否需要,我想知道是否对此有改进。

CustomerForm.vb

Imports System.Data.SqlClient

Public Class CustomerForm
Private objConnection As SqlConnection
Public objDataTable As DataTable = New DataTable()
Public objSqlCommand As SqlCommand = New SqlCommand()
Public editMode As Boolean = False
Public id As String = ""
Public FName As String = ""
Public LName As String = ""
Public PhNumber As String = ""

Public ReadOnly Property Connection As SqlConnection
    Get
        Return Me.objConnection
    End Get
End Property

Dim CS As String = ("server=CASHAMERICA;Trusted_Connection=yes;database=ProductsDatabase2; connection timeout=30")

Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click

    Try
        If editMode = False Then
            If txtFirstName.Text = "" Then
                MessageBox.Show("First Name Is required")
            ElseIf txtLastName.Text = "" Then
                MessageBox.Show("Last Name Is required")
            Else
                Dim con As New SqlConnection(CS)
                con.Open()
                Dim cmd As New SqlCommand("INSERT INTO Customers(FIrstName,LastName,PhoneNumber) VALUES(@FName, @LName, @PhNumber)", con)
                cmd.Parameters.AddWithValue("@FName", txtFirstName.Text)
                cmd.Parameters.AddWithValue("@LName", txtLastName.Text)
                cmd.Parameters.AddWithValue("@PhNumber", txtPhoneNumber.Text)
                cmd.ExecuteNonQuery()
                MessageBox.Show("Customer has been added!")
                con.Close()
            End If
        ElseIf editMode = True Then
            If txtFirstName.Text = "" Then
                MessageBox.Show("First Name Is required")
            ElseIf txtLastName.Text = "" Then
                MessageBox.Show("Last Name Is required")
            Else
                Dim con As New SqlConnection(CS)
                con.Open()
                Dim cmd As New SqlCommand("UPDATE Customers SET FIrstName = @FName, LastName = @LName, PhoneNumber = @PhNumber WHERE Id = @Id", con)
                cmd.Parameters.AddWithValue("@Id", id)
                cmd.Parameters.AddWithValue("@FName", txtFirstName.Text)
                cmd.Parameters.AddWithValue("@LName", txtLastName.Text)
                cmd.Parameters.AddWithValue("@PhNumber", txtPhoneNumber.Text)
                cmd.ExecuteNonQuery()
                MessageBox.Show("Customer has been edited.")
                con.Close()
            End If
        End If

    Catch ex As Exception
        MessageBox.Show(Me, ex.Message, "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try

End Sub

Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
    Me.Close()
End Sub

Private Sub CustomerForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    If editMode = False Then
        GetId()
    Else
        textId.Text = id
        txtFirstName.Text = FName
        txtLastName.Text = LName
        txtPhoneNumber.Text = PhNumber
    End If
End Sub

Private Sub GetId()
    Dim con As New SqlConnection(CS)
    con.Open()
    Dim cmd As New SqlCommand("SELECT MAX(id)+1 FROM Customers")
    textId.Text = FillDataTable().Rows(0)(0).ToString()
    If textId.Text = "" Then
        textId.Text = "1"
    End If

End Sub

Public Property CommandText As String
    Get
        Return CommandText
    End Get
    Set(ByVal value As String)
        CommandText = value
    End Set
End Property

Public Sub OpenDBConnection()
    objConnection = New SqlConnection(CS)
    objConnection.Open()
End Sub


Public Sub CreateCommandObject()
    objSqlCommand = objConnection.CreateCommand()
    objSqlCommand.CommandText = CommandText
    objSqlCommand.CommandType = CommandType.Text
End Sub

Public Function FillDataTable() As DataTable
    objDataTable = New DataTable()
    objSqlCommand.CommandText = CommandText
    objSqlCommand.Connection = objConnection
    objSqlCommand.CommandType = CommandType.Text
    objDataTable.Load(objSqlCommand.ExecuteReader())
    objConnection.Close()
    Return objDataTable
End Function

Public Sub CloseConnection()
    If objConnection IsNot Nothing Then objConnection.Close()
End Sub

End Class

MainForm.vb

Imports System.Windows.Forms.LinkLabel

Public Class MainForm
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
    Me.Close()
End Sub

Private Sub AddToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddToolStripMenuItem.Click
    CustomerForm.ShowDialog()
End Sub

Private Sub AddToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles AddToolStripMenuItem1.Click
    ProductForm.ShowDialog()
End Sub

Private Sub ViewProductsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ViewProductsToolStripMenuItem.Click
    ManageProductsForm.ShowDialog()
End Sub

Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutToolStripMenuItem.Click
    AboutForm.Show()
End Sub

Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'TODO: This line of code loads data into the 'ProductsDatabase2DataSet1.Customers' table. You can move, or remove it, as needed.
    Me.CustomersTableAdapter.Fill(Me.ProductsDatabase2DataSet1.Customers)

End Sub

Private Sub gridCustomers_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles gridCustomers.MouseUp
    Try
        Dim f As CustomerForm = New CustomerForm()
        f.editMode = True
        Dim rowIndex As Integer = gridCustomers.CurrentCell.RowIndex
        f.id = gridCustomers.Rows(rowIndex).Cells("colId").Value.ToString()
        f.FName = gridCustomers.Rows(rowIndex).Cells("colFirstName").Value.ToString()
        f.LName = gridCustomers.Rows(rowIndex).Cells("colLastName").Value.ToString()
        f.PhNumber = gridCustomers.Rows(rowIndex).Cells("colPhoneNumber").Value.ToString()
        f.Show()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub



Private Sub gridCustomers_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles gridCustomers.CellContentClick
    Dim f As CustomerForm = New CustomerForm()
    f.ShowDialog(Me)
    f.editMode = True
End Sub
End Class

错误信息:

客户信息未显示:

【问题讨论】:

  • 我看不到您在哪里设置CommandText 属性,该属性在FillDataTable() 中使用,由GetId() 调用。你还有一个讨厌的错误:CommandText 属性在Set(ByVal value As String) CommandText = value 中递归调用自身(当然,这同样适用于 C# 代码)。使用自动属性或支持字段。使用公共属性而不是公共字段。注意 VB.Net 的默认 Form 实例。
  • 感谢您的反馈,我实际上认为我的代码实际上会比我想象的要糟糕得多。我打电话给 CustomerForm 2 次,发现我不需要 f.ShowDialog(Me)
  • 是的,您在gridCustomers_MouseUpgridCustomers_CellContentClick 中也存在重叠代码问题(另外,f.editMode = TrueShowDialog() 之后调用,因此未设置)。因此,单击单元格将调用相同的表单两次(这应该很明显)。先把其他的东西修好,游戏就结束了。
  • 您知道您可以使用 DataTable、DataAdapter 和绑定来编辑和添加到 DataGridView 的数据。检查更新和填充方法。没有第二个表单和更少的代码。
  • 添加客户时出现错误,在调试时出现错误“System.InvalidOperationException: 'ExecuteReader: Connection property has not been initialized.”在objDataTable.Load(objSqlCommand.ExecuteReader())。编辑显示没有错误。我也确实将 CommandText 属性更改为Public Property CommandText As String。我注释掉了gridCustomers_CellContentClick 方法,因为没有它它仍然可以工作。我不知道我可以点击任何地方进行编辑,所以我什至没有使用链接标签编辑。

标签: vb.net oledb sqldatareader c#-to-vb.net


【解决方案1】:

如前所述,您似乎有几件事可能发生。

我要更改的第一件事是您的公共 sql 对象。你不需要他们公开。如果您在多个地方使用相同的对象,也会增加出现问题的机会。

SqlCommand、SqlConnection 和 SqlDataAdapter 可以在使用后立即处置(在大多数情况下)。

处理所有这些的一种简单方法是将所有内容放入 USING 块中。

Dim sqlResult As New Datatable()

Using cn As New SqlConnection("Connection String here"),
                  cmd As New SqlCommand(sql, cn),
                  adapt As New SqlDataAdapter(cmd)

            cn.Open()

            'Handle stored procedure vs select options
            If sql.Contains("SELECT") Then
                cmd.CommandType = CommandType.Text
            Else
                cmd.CommandType = CommandType.StoredProcedure
            End If

            'If parameters passed, else comment out
            cmd.Parameters.AddWithValue("@parameterName", parameterValue)

            sqlResult = New DataTable(cmd.CommandText)
            adapt.Fill(sqlResult)

        End Using

现在,一旦您的数据表被填满,您的所有对象都会被处理掉。

*此示例使用数据表,但与 sql 对象交互的任何内容都是相同的想法。

如果实施,您可能会发现某些对象没有被正确处理或初始化。

另一种测试哪里出错的方法是查询错误之前或周围的 SQL 对象的状态,以查看是否设置不正确或未初始化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 2011-09-07
    • 2021-01-12
    相关资源
    最近更新 更多