0

我可以毫无问题地将我的记录添加到我的数据库中,但是我无法将其自动显示到我的 datagridview 中。

为了让我在我的 datagridview 中查看我的记录,我需要关闭并重新启动整个内容以使其显示。有没有我错过的代码?

 Private Sub btnAddEmp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddEmp.Click
    Dim tranEmployee As SqlClient.SqlTransaction
    sAdapter = New SqlDataAdapter(cmdEmployee)
    Dim strID As String
    Dim strName As String

    Dim strPosition As String
    Dim strContactNo As String
    Dim strAddress As String
    Dim strDOB As String
    Dim strGender As String
    Dim strSQL As String

    conn.Open()


    strID = mskEmployeeID.Text
    strName = txtEmpName.Text
    strPosition = cboEmpPosition.Text
    strContactNo = mskEmpDOB.Text
    strDOB = mskEmpDOB.Text
    strAddress = txtEmpAddress.Text
    If radEmpMale.Checked Then
        strGender = "Male"
    Else
        strGender = "Female"
    End If


    strSQL = "INSERT INTO Users(userID,userName,userPosition,userGender,userDOB,userAddress)" & _
        "VALUES(@ID,@NAME,@POSITION,@GENDER,@DOB,@ADDRESS)"

    tranEmployee = conn.BeginTransaction() 

    With cmdEmployee
        .Transaction = tranEmployee
        .CommandText = strSQL
        .Parameters.AddWithValue("@ID", strID)
        .Parameters.AddWithValue("@NAME", strName)
        .Parameters.AddWithValue("@POSITION", strPosition)
        .Parameters.AddWithValue("@GENDER", strGender)
        .Parameters.AddWithValue("@DOB", strDOB)
        .Parameters.AddWithValue("@ADDRESS", strAddress)
        .Connection = conn

    End With

    Try
        cmdEmployee.ExecuteNonQuery()
        tranEmployee.Commit()

    Catch ex As Exception
        tranEmployee.Rollback()
        MessageBox.Show(ex.Message)
    Finally
        conn.Close()
    End Try

End Sub
4

2 回答 2

1

您显示的代码将成功地将记录添加到数据库中,但它不会尝试刷新 UI 中的任何内容。将网格绑定到数据库中的记录的代码在哪里?该代码运行后需要再次运行该代码。

我假设代码存在于表单的某种初始化程序中。也许某种加载事件?您需要将该网格绑定代码移动到它自己的函数中,并从加载事件和此单击事件结束时调用它,可能就在您提交事务的行之后。

于 2013-07-16T20:23:05.340 回答
0

您需要再次调用您的 select 语句子例程。您从数据库中提取信息的语句。

Try
    cmdEmployee.ExecuteNonQuery()
    tranEmployee.Commit()
Catch ex As Exception
    tranEmployee.Rollback()
    MessageBox.Show(ex.Message)
Finally
    conn.Close()
    selectUsers()
End Try
于 2013-07-16T20:27:21.747 回答