添加到数据库后,在datagridview中显示记录

时间:2013-07-16 20:16:38

标签: sql database vb.net

我可以毫无问题地将我的记录添加到我的数据库中,但是我无法自动将其显示到我的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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

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