Oregon State University
Oregon State University Home Page

BA 371: VB GUI-DB Communication





Private Sub QueryButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs)Handles QueryButton.Click
'database query code will go here...
End Sub


Private Sub CloseButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs)Handles CloseButton.Click
Close()
End Sub

However, since in a Windows app we cannot add an (uninstantiated) class that holds the Main() and then set the startup object to Main(), we'll add the connecting code to the form's QueryForm_Load() method (its skeleton is generated when you double click on the form in design mode) and we add the disconnecting code to the QueryForm_FormClosing() method (which we add ourselves).
Private ConnectString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=c:\temp\foo.mdb"

Private Connection as
New System.Data.OleDb.OleDbConnection(ConnectString)
   Try
Connection.Open()
Catch f As System.Exception
MsgBox("Problem opening database..." + f.Message)
System.Environment.Exit(1)
End Try
    Private sub QueryForm_FormClosing(ByVal sender as Object, Byval e as System.Windows.Forms.FormClosingEventArgs) _
handles Me.FormClosing
Try
Connection.Close()
Catch g As System.Exception
MsgBox("Problem closing database..." + g.Message)
System.Environment.Exit(1)
End Try
End Sub

Private Sub QueryButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles QueryButton.Click

Dim SQLCommand As System.Data.OleDb.OleDbCommand
Dim SQLDataReader As System.Data.OleDb.OleDbDataReader
Dim result_string As String

SQLCommand = New System.Data.OleDb.OleDbCommand("select name from foo", Connection)

Try
SQLDataReader = SQLCommand.ExecuteReader()
Catch h As Exception
MsgBox("Problem in ExecuteReader()..." + h.Message)
Connection.Close()
System.Environment.Exit(1)
End Try

Try
While SQLDataReader.Read()
result_string = SQLDataReader.GetString(0)
ResultList.Items.Add(result_string)
End while
SQLDataReader.Close()
Catch l As Exception
MsgBox("Problems reading data from the SQlDataReader..." + l.Message)
Connection.Close()
System.Environment.Exit(1)
End Try
End Sub


Private Sub ClearButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ClearButton.Click
ResultList.Items.Clear()
End Sub