开发者

VB 2008 with MsAccess connection on Multiple Forms

I have a VB Solution with a dozen forms trying to implement invoice system.

My main form (Say Form1) only has a design to create , Edit or Delete Customers. My form 2 will be opened if Create button is clicked. In my form 2, I have textboxes where user can enter Customer details and click on SAVE. My doubt is here....

On clicking this SAVE button in Form 2, I want a INSERT command to happen on the MSAccess's Database table called Customer (which I have 开发者_运维技巧already created... this table does not have any records as of now).

In my form 1, I added a MSAccess Database with a Connection String. In my Form1's code I have code like this

Public Class Form1

      'Code specific to Form1's elements

End Class

Public Class Connection
    Private Shared connection As OleDb.OleDbConnection

    Public Shared ReadOnly Property Instance() As OleDb.OleDbConnection
        Get
            If connection Is Nothing Then
                connection = New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Invoice.mdb")
            End If
            Return connection
        End Get
    End Property
End Class

In my form 2, I have some code like this ... when SAVE is clicked

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim myConnection As OleDb.OleDbConnection
        myConnection = Connection.Instance

    End Sub

I got this piece of code from this link [1]: vb.net - sharing mdb access connection among multiple forms

Now, I do not know what more code does this require to INSERT records from my text box into the Customer table's fields. Can anyone help, please?


Once you have the connection, you can do a normal insert into the Access table. You didn't specify if you were doing the insert by a string of SQL, or via a Stored Procedure. For simplicity my example uses the former, however I strongly recommend either a parameterized query (if you're doing a string of SQL) or a stored procedure to prevent SQL Injection attacks.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Try

        Dim myConnection As OleDb.OleDbConnection = Connection.Instance

        myConnection.Open()

        Dim sqlString As String = "" ' Put your insert SQL here
        Dim myCommand As New OleDbCommand(sqlString, myConnection)

        Dim rows As Integer = myCommand.ExecuteNonQuery
    Catch ex As Exception
        // Handle any errors here
    Finally
        myConnection.Close()
    End Try

End Sub
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜