Link to home
Start Free TrialLog in
Avatar of matthewsampson
matthewsampson

asked on

Open Database into Datagrid from OpenFileDialog

Hi Guys,

I've got several access databases which have the same fields but different data.
I want to be able to open the database into a datagrid, which I can do if I refer to the exact file location in the code, but what I'm trying to do is to allow my users to go to File, Open and select the file and click open (as you would with a document in word, excel, etc...).

Eventually, the datagrid would then show all the records in the database which can then be double clicked on to open a form to edit the record.

Any help someone can give would be greatly appreciated.

Many Thanks

Matt
------------
Anglia University, Cambridge

Avatar of Howard Cantrell
Howard Cantrell
Flag of United States of America image

Here is a datagrid app that I have been playing with for the pass few months with tooltips, color change on cell edit, etc...

'FORM 1

Imports System.Data
Imports System.Drawing.Graphics

Public Class frmComBuilder
    Inherits System.Windows.Forms.Form
    Dim bHit As Boolean

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call
        Me.Top = 0
        Me.Left = 100
        InitializeDataBase()
        Me.Show()
    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents dgInventory As System.Windows.Forms.DataGrid
    Friend WithEvents cmdExit As System.Windows.Forms.Button
    Friend WithEvents cmdOk As System.Windows.Forms.Button
    Friend WithEvents cmdAdd As System.Windows.Forms.Button
    Friend WithEvents cmdDelete As System.Windows.Forms.Button
    Friend WithEvents cmdUpdate As System.Windows.Forms.Button
    Friend WithEvents lblTable As System.Windows.Forms.Label
    Friend WithEvents lblQty As System.Windows.Forms.Label
    Friend WithEvents lblDescription As System.Windows.Forms.Label
    Friend WithEvents txtQty As System.Windows.Forms.TextBox
    Friend WithEvents txtDescription As System.Windows.Forms.TextBox
    Friend WithEvents ToolTip As System.Windows.Forms.ToolTip
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Me.dgInventory = New System.Windows.Forms.DataGrid
        Me.cmdExit = New System.Windows.Forms.Button
        Me.cmdOk = New System.Windows.Forms.Button
        Me.cmdAdd = New System.Windows.Forms.Button
        Me.cmdDelete = New System.Windows.Forms.Button
        Me.cmdUpdate = New System.Windows.Forms.Button
        Me.lblTable = New System.Windows.Forms.Label
        Me.lblQty = New System.Windows.Forms.Label
        Me.lblDescription = New System.Windows.Forms.Label
        Me.txtQty = New System.Windows.Forms.TextBox
        Me.txtDescription = New System.Windows.Forms.TextBox
        Me.ToolTip = New System.Windows.Forms.ToolTip(Me.components)
        CType(Me.dgInventory, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'dgInventory
        '
        Me.dgInventory.CaptionVisible = False
        Me.dgInventory.DataMember = ""
        Me.dgInventory.HeaderForeColor = System.Drawing.SystemColors.ControlText
        Me.dgInventory.Location = New System.Drawing.Point(16, 100)
        Me.dgInventory.Name = "dgInventory"
        Me.dgInventory.Size = New System.Drawing.Size(456, 196)
        Me.dgInventory.TabIndex = 0
        '
        'cmdExit
        '
        Me.cmdExit.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.cmdExit.Location = New System.Drawing.Point(104, 312)
        Me.cmdExit.Name = "cmdExit"
        Me.cmdExit.Size = New System.Drawing.Size(68, 32)
        Me.cmdExit.TabIndex = 1
        Me.cmdExit.Text = "&Exit"
        '
        'cmdOk
        '
        Me.cmdOk.Enabled = False
        Me.cmdOk.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.cmdOk.Location = New System.Drawing.Point(16, 312)
        Me.cmdOk.Name = "cmdOk"
        Me.cmdOk.Size = New System.Drawing.Size(72, 32)
        Me.cmdOk.TabIndex = 2
        Me.cmdOk.Text = "&Ok"
        '
        'cmdAdd
        '
        Me.cmdAdd.Enabled = False
        Me.cmdAdd.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.cmdAdd.Location = New System.Drawing.Point(184, 312)
        Me.cmdAdd.Name = "cmdAdd"
        Me.cmdAdd.Size = New System.Drawing.Size(72, 32)
        Me.cmdAdd.TabIndex = 3
        Me.cmdAdd.Text = "&Add"
        '
        'cmdDelete
        '
        Me.cmdDelete.Enabled = False
        Me.cmdDelete.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.cmdDelete.Location = New System.Drawing.Point(268, 312)
        Me.cmdDelete.Name = "cmdDelete"
        Me.cmdDelete.Size = New System.Drawing.Size(72, 32)
        Me.cmdDelete.TabIndex = 4
        Me.cmdDelete.Text = "&Delete"
        '
        'cmdUpdate
        '
        Me.cmdUpdate.Enabled = False
        Me.cmdUpdate.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.cmdUpdate.Location = New System.Drawing.Point(356, 312)
        Me.cmdUpdate.Name = "cmdUpdate"
        Me.cmdUpdate.Size = New System.Drawing.Size(80, 32)
        Me.cmdUpdate.TabIndex = 5
        Me.cmdUpdate.Text = "&UpDate"
        '
        'lblTable
        '
        Me.lblTable.Font = New System.Drawing.Font("Times New Roman", 15.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblTable.Location = New System.Drawing.Point(28, 16)
        Me.lblTable.Name = "lblTable"
        Me.lblTable.Size = New System.Drawing.Size(412, 28)
        Me.lblTable.TabIndex = 6
        '
        'lblQty
        '
        Me.lblQty.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblQty.Location = New System.Drawing.Point(24, 68)
        Me.lblQty.Name = "lblQty"
        Me.lblQty.Size = New System.Drawing.Size(84, 16)
        Me.lblQty.TabIndex = 7
        Me.lblQty.Text = "Qty. On Hand:"
        '
        'lblDescription
        '
        Me.lblDescription.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblDescription.Location = New System.Drawing.Point(192, 68)
        Me.lblDescription.Name = "lblDescription"
        Me.lblDescription.Size = New System.Drawing.Size(76, 16)
        Me.lblDescription.TabIndex = 8
        Me.lblDescription.Text = "Description:"
        '
        'txtQty
        '
        Me.txtQty.Location = New System.Drawing.Point(112, 64)
        Me.txtQty.Name = "txtQty"
        Me.txtQty.ReadOnly = True
        Me.txtQty.Size = New System.Drawing.Size(48, 20)
        Me.txtQty.TabIndex = 9
        Me.txtQty.Text = ""
        '
        'txtDescription
        '
        Me.txtDescription.Location = New System.Drawing.Point(268, 64)
        Me.txtDescription.Name = "txtDescription"
        Me.txtDescription.ReadOnly = True
        Me.txtDescription.Size = New System.Drawing.Size(336, 20)
        Me.txtDescription.TabIndex = 10
        Me.txtDescription.Text = ""
        '
        'ToolTip
        '
        Me.ToolTip.AutomaticDelay = 200
        Me.ToolTip.AutoPopDelay = 200
        Me.ToolTip.InitialDelay = 200
        Me.ToolTip.ReshowDelay = 40
        '
        'frmComBuilder
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(488, 353)
        Me.Controls.Add(Me.txtDescription)
        Me.Controls.Add(Me.txtQty)
        Me.Controls.Add(Me.lblDescription)
        Me.Controls.Add(Me.lblQty)
        Me.Controls.Add(Me.lblTable)
        Me.Controls.Add(Me.cmdUpdate)
        Me.Controls.Add(Me.cmdDelete)
        Me.Controls.Add(Me.cmdAdd)
        Me.Controls.Add(Me.cmdOk)
        Me.Controls.Add(Me.cmdExit)
        Me.Controls.Add(Me.dgInventory)
        Me.MaximizeBox = False
        Me.Name = "frmComBuilder"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "frmEditInventory"
        CType(Me.dgInventory, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)

    End Sub
#End Region
    Private Sub InitializeDataBase()
        Cursor.Current = Cursors.WaitCursor
        '*********** FOR ADO.NET **********************
        Dim sSQL As String = "SELECT * FROM " & sTableName
        AccessConnection(sSQL)

        Dim cb As System.Data.OleDb.OleDbCommandBuilder
        ' Optional command builder which automates the process of building each command
        ' by hand. This only works if the SelectCommand issued to the data
        ' adapter contains a primary key. USE EITHER ONE, BUT NOT BOTH
        ' Use cb.GetUpdateCommand.CommandText to view auto-generated SQL statements
        cb = New System.Data.OleDb.OleDbCommandBuilder(myDataAdapter)
        Dim mystr As String = cb.GetUpdateCommand.CommandText
        Dim val As Integer = cb.GetUpdateCommand.Parameters.Count

        ' Bind DataGrid control to this dataset            
        dgInventory.SetDataBinding(ds, sTableName)

        FillDataGrid()
        Cursor.Current = Cursors.Default
    End Sub
    Private Sub FillDataGrid()
        Dim sDescription As String

        dgInventory.DataSource = ds.Tables(sTableName)

        With grdTableStyle1
            .AlternatingBackColor = Color.GhostWhite
            .BackColor = Color.GhostWhite
            .ForeColor = Color.MidnightBlue
            .GridLineColor = Color.RoyalBlue
            .HeaderBackColor = Color.MidnightBlue
            .HeaderFont = New Font("Tahoma", 8.0!, FontStyle.Bold)
            .HeaderForeColor = Color.Lavender
            .SelectionBackColor = Color.Teal
            .SelectionForeColor = Color.PaleGreen
            ' Do not forget to set the MappingName property.
            ' Without this, the DataGridTableStyle properties
            ' and any associated DataGridColumnStyle objects
            ' will have no effect.
            .MappingName = sTableName
            .PreferredColumnWidth = 125
            .PreferredRowHeight = 16
        End With
        Dim grdColStyle1 As New DataGridTextBoxColumn
        With grdColStyle1
            .HeaderText = "ID"
            .MappingName = "ContactID"
            .Width = 40
            .ReadOnly = True
        End With

        With grdColStyle2
            .HeaderText = "Name"
            .MappingName = "Name"
            AddHandler grdColStyle2.TextBox.TextChanged, AddressOf dataGrid_TextChanged
            'test with
            iTag = 0
            Select Case iTag
                Case 0
                    sDescription = "Contacts"
                    .Width = 150
                Case 1
                    sDescription = "Music Material"
                    .Width = 450
            End Select
            Me.dgInventory.Width = (260 + .Width)
            Me.Width = Me.dgInventory.Width + 50
        End With

        With grdColStyle3
            .HeaderText = "On Hand"
            .MappingName = "OnHand"
            .Width = 60
            AddHandler grdColStyle3.TextBox.TextChanged, AddressOf dataGrid_TextChanged
        End With

        Dim grdColStyle4 As New DataGridTextBoxColumn
        With grdColStyle4
            .HeaderText = "Last Change Date"
            .MappingName = "LastChange"
            .Width = 120
            .ReadOnly = True
        End With
        Me.Text = sTableName
        Me.lblTable.Text = sDescription
        Me.txtDescription.Width = (Me.dgInventory.Width - 250)
        ' Add the style objects to the table style's collection of
        ' column styles. Without this the styles do not take effect.        
        grdTableStyle1.GridColumnStyles.AddRange _
            (New DataGridColumnStyle() {grdColStyle1, grdColStyle2, grdColStyle3, grdColStyle4})

        dgInventory.TableStyles.Add(grdTableStyle1)
        '    dgInventory.ReadOnly = True

        dgInventory.Select(0)
        txtQty.Text = dgInventory.Item(dgInventory.CurrentRowIndex, 2)
        txtDescription.Text = dgInventory.Item(dgInventory.CurrentRowIndex, 1)
    End Sub
#Region " My Click Events Code "
    Private Sub cmdOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdOk.Click
        '*****************
        'BEGIN EDIT CODE go get primary key
        Dim pk(0) As DataColumn
        pk(0) = ds.Tables(sTableName).Columns("ContactID")
        ds.Tables(sTableName).PrimaryKey = pk

        '********* Use this for single edit mode **************
        'CurRow = DS.Tables("Inventory_" & sTableName).Rows.Find(dgInventory.Item(dgInventory.CurrentRowIndex, 0))
        'CurRow.BeginEdit()
        'CurRow("OnHand") = dgInventory.Item(dgInventory.CurrentRowIndex, 2)
        'CurRow("Description") = dgInventory.Item(dgInventory.CurrentRowIndex, 1)
        'CurRow.EndEdit()
        'MsgBox("Record edited successfully")
        'CurRow.AcceptChanges()
        'myDataAdapter.Update(DS.Tables("Inventory_" & sTableName))
        'END EDIT CODE  
        '**********************************************
        '********* Edits the whole datagrid ************
        Dim icnt As Short = 0
        For Each CurRow In ds.Tables(sTableName).Rows
            CurRow.BeginEdit()
            CurRow("OnHand") = dgInventory.Item(icnt, 2)
            CurRow("Name") = dgInventory.Item(icnt, 1)
            icnt += 1
            CurRow.EndEdit()
        Next
        myDataAdapter.Update(ds.Tables(sTableName))
        MsgBox("Records edited successfully")
        dgInventory.Refresh()
        cmdUpdate.Enabled = False
        cmdAdd.Enabled = False
        cmdDelete.Enabled = False
        cmdOk.Enabled = False
    End Sub
    Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
        dgInventory.ReadOnly = False
        Me.BindingContext(DS, sTableName).Position = DS.Tables(sTableName).Rows.Count - 1
        '     "To save your changes to the Windows Forms DataGrid, press 'update'."
        ' dgInventory.Refresh()
        cmdUpdate_Click(sender, e)
    End Sub
    Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDelete.Click
        DS.Tables(sTableName).Rows(Me.BindingContext(DS, sTableName).Position).Delete()
        'DS.Tables(sTableName).Rows.Item(dgInventory.CurrentRowIndex).Delete()
        'lblInfo.Text = To save your changes you must click 'Update'."
        cmdUpdate_Click(sender, e)
    End Sub
    Private Sub cmdUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdUpdate.Click
        Try
            myDataAdapter.Update(DS, sTableName)
            '  dg.ReadOnly = True
            'lblInfo.Text = "Changes to the Windows Forms DataGrid have been saved.
        Catch ex As SystemException
            MsgBox(ex.StackTrace & ex.Message, MsgBoxStyle.Critical, "General Error")
        End Try
        MsgBox("Records edited successfully")
        ' Create and fill dataset
        ResetGridColor()
        DS.Clear()
        DS = New DataSet(sTableName)
        myDataAdapter.Fill(DS, sTableName)
        ' Bind DataGrid control to this dataset            
        dgInventory.SetDataBinding(DS, sTableName)
        dgInventory.Refresh()
        cmdOk.Enabled = True
        cmdUpdate.Enabled = False
    End Sub
    Private Sub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click
        ''    Conn.Close()
        ' Determine the active child form.
        'Dim activeChild As Form = Me.ActiveMdiChild
        'activeChild = ActiveForm
        '' If there is an active child form, find the active control, which
        '' in this example should be a RichTextBox.
        'If (activeChild Is Nothing) Then
        '    Try
        '        ' If activeChild.Name = "frmInventory" Then
        '        activeChild.WindowState = FormWindowState.Minimized
        '        activeChild.Show()
        '        '  End If
        '    Catch
        '        MessageBox.Show("You need to select a RichTextBox.")
        '    End Try
        'End If
        Me.Close()
    End Sub
#End Region

#Region "Datagrid TextBox Code"
    Private Sub dataGrid_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim dgcc As DataGridCell = Me.dgInventory.CurrentCell
        Dim tb As TextBox = GetEmbeddedTextBox(dgcc.ColumnNumber)
        If Not (tb Is Nothing) Then
            Dim oldValue As String = Me.dgInventory(dgcc).ToString()
            Dim newValue As String = tb.Text
            If newValue <> oldValue Then
                GetEmbeddedDGTextBox(dgcc.ColumnNumber).AddRow = Me.dgInventory.CurrentRowIndex
            End If
        End If
    End Sub
    Private Function GetEmbeddedTextBox(ByVal col As Integer) As TextBox
        Dim tbc As DataGridTextBoxColumn = Me.dgInventory.TableStyles(sTableName).GridColumnStyles(col)
        If Not (tbc Is Nothing) AndAlso tbc.TextBox.Modified Then
            Return tbc.TextBox
        End If
        Return Nothing
    End Function
    Private Function GetEmbeddedDGTextBox(ByVal col As Integer) As DGColorTextBox
        Dim tbc As DGColorTextBox = Me.dgInventory.TableStyles(sTableName).GridColumnStyles(col)
        If Not (tbc Is Nothing) AndAlso tbc.TextBox.Modified Then
            Return tbc
        End If
        Return Nothing
    End Function
#End Region

#Region "Datagrid Mouse Events"
    Private Sub dgInventory_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgInventory.MouseUp
        Try
            txtQty.Text = dgInventory.Item(dgInventory.CurrentRowIndex, 2)
            txtDescription.Text = dgInventory.Item(dgInventory.CurrentRowIndex, 1)
            'bHit id used for skipping over the read only columns
            If bHit = False Then
                GetCellValue(sender, e)       'Go get cell values
                grdColStyle2.GetScollBar()
            End If
        Catch ex As InvalidCastException
            'Skip DBNULL
        Catch ex As SystemException
            MsgBox(ex.StackTrace & ex.Message, MsgBoxStyle.Critical, "General Error")
        End Try
    End Sub
    Private Sub Dg_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles dgInventory.MouseDown
        Dim selectedCell As System.Windows.Forms.DataGridCell
        selectedCell = Me.dgInventory.CurrentCell

        Dim myGrid As DataGrid = CType(sender, DataGrid)
        hti = myGrid.HitTest(e.X, e.Y)
        Select Case hti.Type
            Case System.Windows.Forms.DataGrid.HitTestType.None
                Console.WriteLine("You clicked the background.")
            Case System.Windows.Forms.DataGrid.HitTestType.Cell
                cmdUpdate.Enabled = True
                cmdAdd.Enabled = True
                cmdDelete.Enabled = True
                If hti.Column = 0 Or hti.Column = 3 Then bHit = True Else bHit = False
                Console.WriteLine("You clicked cell at row " & hti.Row & ", col " & hti.Column)
            Case System.Windows.Forms.DataGrid.HitTestType.ColumnHeader
                Console.WriteLine("You clicked the column header for column " & hti.Column)
            Case System.Windows.Forms.DataGrid.HitTestType.RowHeader
                Console.WriteLine("You clicked the row header for row " & hti.Row)
            Case System.Windows.Forms.DataGrid.HitTestType.ColumnResize
                Console.WriteLine("You clicked the column resizer for column " & hti.Column)
            Case System.Windows.Forms.DataGrid.HitTestType.RowResize
                Console.WriteLine("You clicked the row resizer for row " & hti.Row)
            Case System.Windows.Forms.DataGrid.HitTestType.Caption
                Console.WriteLine("You clicked the caption")
            Case System.Windows.Forms.DataGrid.HitTestType.ParentRows
                Console.WriteLine("You clicked the parent row")
        End Select
    End Sub
    Private Sub dgInventory_MouseMove(ByVal sender As System.Object, ByVal e As MouseEventArgs) Handles dgInventory.MouseMove
        Dim sCost As String
        Dim sUnits As String
        Dim str As String
        Try
            hti = dgInventory.HitTest(e.X, e.Y)
            Select Case hti.Type
                Case System.Windows.Forms.DataGrid.HitTestType.Cell
                    sCost = dgInventory.Item(hti.Row, 1)  'Column 1
                    sUnits = dgInventory.Item(hti.Row, 2) 'Column 2
                    str = "Cost: " & sCost & vbCr & "  Units In Stock: " & sUnits
                    ToolTip.SetToolTip(dgInventory, str)
                    RefreshRow(hti.Row)
            End Select
        Catch
        End Try
    End Sub
    Private Function GetCellValue(ByVal sender As Object, ByVal e As MouseEventArgs)
        ' Use the HitTest method to get a HitTestInfo object.
        Dim hi As DataGrid.HitTestInfo
        Dim grid As DataGrid = CType(sender, DataGrid)
        hi = grid.HitTest(e.X, e.Y)
        ' Test if the clicked area was a cell.
        If hi.Type = DataGrid.HitTestType.Cell Then
            ' If it's a cell, get the GridTable and CurrencyManager of the clicked table.        
            Dim dgt As DataGridTableStyle = grid.TableStyles(0)
            Dim myCurrencyManager As CurrencyManager = CType(Me.BindingContext(DS.Tables(dgt.MappingName)), CurrencyManager)
            ' Set the Position to the Row.
            myCurrencyManager.Position = hi.Row
            ' Get the clicked DataGridTextBoxColumn.
            Dim gridCol As DGColorTextBox = CType(dgt.GridColumnStyles(hi.Column), DGColorTextBox)
            ' Invoke the GetColumnValueAtRow.
            Return oCellValue = gridCol.GetColValueAtRow(myCurrencyManager, hi.Row)
        End If
    End Function
#End Region

#Region "Keypress and Validating"
    Private Sub txtQty_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtQty.Validating, txtDescription.Validating
        dgInventory.Item(dgInventory.CurrentRowIndex, 2) = txtQty.Text
        dgInventory.Item(dgInventory.CurrentRowIndex, 1) = txtDescription.Text
    End Sub
    Private Sub txtQty_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtQty.KeyPress
        Dim KeyAscii As Short = Asc(e.KeyChar)
        Select Case KeyAscii
            Case System.Windows.Forms.Keys.Back   'same as 8
                KeyAscii = 0
            Case Keys.Enter, Keys.Tab             'same as 13
                dgInventory.Item(dgInventory.CurrentRowIndex, 2) = txtQty.Text
                dgInventory.Item(dgInventory.CurrentRowIndex, 1) = txtDescription.Text
                SendKeys.Send("{TAB}")
            Case 32 To 47
                e.Handled = True
            Case 48 To 57              'Numbers
            Case Else
                e.Handled = True
        End Select
    End Sub
    Private Sub txtDescription_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtDescription.KeyPress
        Dim KeyAscii As Short = Asc(e.KeyChar)
        Select Case KeyAscii
            Case System.Windows.Forms.Keys.Back   'same as 8
                KeyAscii = 0
            Case Keys.Enter, Keys.Tab             'same as 13
                dgInventory.Item(dgInventory.CurrentRowIndex, 2) = txtQty.Text
                dgInventory.Item(dgInventory.CurrentRowIndex, 1) = txtDescription.Text
                SendKeys.Send("{TAB}")
            Case 32 To 47
                e.Handled = True
            Case 48 To 57              'Numbers
            Case 65 To 90, 97 To 122   'Letters
            Case Else
                e.Handled = True
        End Select
    End Sub
    Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
        Const WM_KEYDOWN As Integer = &H100
        Const WM_SYSKEYDOWN As Integer = &H104

        Try
            If ((msg.Msg = WM_KEYDOWN) Or (msg.Msg = WM_SYSKEYDOWN)) Then
                Select Case (keyData)
                    Case Keys.F9
                        txtQty.Text = dgInventory.Item(dgInventory.CurrentRowIndex, 2)
                        txtDescription.Text = dgInventory.Item(dgInventory.CurrentRowIndex, 1)
                    Case Keys.Right, Keys.Left, Keys.Down, Keys.Up, Keys.Tab
                        txtQty.Text = dgInventory.Item(dgInventory.CurrentRowIndex, 2)
                        txtDescription.Text = dgInventory.Item(dgInventory.CurrentRowIndex, 1)
                        'dgInventory.Item(dgInventory.CurrentRowIndex, 2) = txtQty.Text
                        'dgInventory.Item(dgInventory.CurrentRowIndex, 1) = txtDescription.Text
                    Case Keys.A To Keys.Z
                    Case Keys.NumPad0 To Keys.NumPad9, Keys.D0 To Keys.D9
                    Case (Keys.Control Or Keys.M)
                        '   Me.Parent.Text = "<CTRL> + M Captured"
                    Case (Keys.Alt Or Keys.Z)
                        '  Me.Parent.Text = "<ALT> + Z Captured"
                End Select
            End If
        Catch ex As InvalidCastException
            'Skip DBNULL
        Catch ex As SystemException
            MsgBox(ex.StackTrace & ex.Message, MsgBoxStyle.Critical, "General Error")
        End Try
        Return MyBase.ProcessCmdKey(msg, keyData)
    End Function
#End Region

#Region "Helper Methods"
    ' Forces a repaint of given row.
    Private Sub RefreshRow(ByVal row As Integer)
        Dim rect As Rectangle = Me.dgInventory.GetCellBounds(row, 0)
        rect = New Rectangle(rect.Right, rect.Top, Me.dgInventory.Width, rect.Height)
        Me.dgInventory.Invalidate(rect)
    End Sub 'RefreshRow
    Private Sub ResetGridColor()
        grdColStyle2.ClearGridColors()
        grdColStyle3.ClearGridColors()
    End Sub
#End Region

End Class


'MODULE

Imports System.IO
Imports System.Data
Imports System.Windows.Forms
Module ModDatagrid
#Region " Global Var's"
    Public iTag As Short
    Public DS As DataSet
    Public CurRow As DataRow
    Public oCellValue As Object            'Holds the cell value
    Public g_lngCurrentRow As Long
    Public g_lngTotalRows As Long
    Public g_strAppPath As String
    Public strAppPath = Directory.GetCurrentDirectory()
    Public grdTableStyle1 As New DataGridTableStyle
    Public grdColStyle2 As New DGColorTextBox
    Public grdColStyle3 As New DGColorTextBox
    Public myDataAdapter As OleDb.OleDbDataAdapter
    Public hti As DataGrid.HitTestInfo
    Public sTableName As String = "Contacts"
    Public sDBPass As String = ""
    Public sUSERid As String = ""
#End Region
    Public Sub AccessConnection(ByVal SQL As String)
        Try
            Dim strConnectionString As String
            strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
             "Data Source=Book.mdb;" & "User ID=" & sUSERid & ";" & _
             "Jet OLEDB:Database Password=" & sDBPass
            Dim Con As New System.Data.OleDb.OleDbConnection(strConnectionString)
            myDataAdapter = New System.Data.OleDb.OleDbDataAdapter(SQL, Con)
            Con.Open()
            ' Create and fill dataset
            DS = New DataSet(sTableName)
            myDataAdapter.Fill(DS, sTableName)
            Con.Close()
        Catch Ex As Exception
            MsgBox("Exception: " & Ex.Message & "  " & Ex.ToString, MsgBoxStyle.Critical)
        End Try
    End Sub
End Module


'CLASS

Option Explicit On

Imports System
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms
Public Class DGColorTextBox
    Inherits DataGridTextBoxColumn

    Dim _row As New System.Collections.ArrayList
    Dim bClear As Boolean = False
    Public Sub New()
        MyBase.New()
    End Sub
    Public Property AddRow() As Integer
        Get
        End Get
        Set(ByVal Value As Integer)
            _row.Add(Value)
        End Set
    End Property
    Public Sub ClearGridColors()
        _row.Clear()
        bClear = True
    End Sub
    Public Sub GetScollBar()
        Dim g As Graphics = Me.TextBox.CreateGraphics()
        Dim size As SizeF = g.MeasureString(Me.TextBox.Text, Me.TextBox.Font)
        Try
            If Me.TextBox.Text = CType(Me.TextBox.Text, Integer) Then
                Me.TextBox.ScrollBars = ScrollBars.None
            End If
        Catch ex As Exception
            If CInt(size.Width) > Me.TextBox.Width Then
                Me.TextBox.ScrollBars = ScrollBars.Vertical
                Me.TextBox.Refresh()
            Else
                Me.TextBox.ScrollBars = ScrollBars.None
            End If
        End Try
    End Sub
    Public Function GetColValueAtRow(ByVal cm As CurrencyManager, ByVal rowNum As Integer) As Object
        Return Me.GetColumnValueAtRow(cm, rowNum)
    End Function
    Protected Overloads Overrides Sub Paint(ByVal g As Graphics, ByVal bounds As Rectangle, ByVal source As CurrencyManager, ByVal rowNum As Integer, ByVal backBrush As Brush, ByVal foreBrush As Brush, ByVal alignToRight As Boolean)
        ' the idea is to conditionally set the foreBrush and/or backbrush
        ' depending upon some crireria on the cell value
        Dim o As Object
        Try
            If _row.Contains(rowNum) Then
                '   backBrush = New LinearGradientBrush(bounds, Color.FromArgb(255, 200, 200), Color.FromArgb(128, 20, 20), LinearGradientMode.BackwardDiagonal)
                'Blue to Green
                backBrush = New LinearGradientBrush(bounds, Color.FromArgb(120, 0, 255, 0), Color.FromArgb(120, 0, 0, 255), LinearGradientMode.BackwardDiagonal)
                ' backBrush = New SolidBrush(Color.Silver)
                foreBrush = New SolidBrush(Color.White)
            End If
            If bClear = True Then
                backBrush = New SolidBrush(Color.GhostWhite)
                foreBrush = New SolidBrush(Color.MidnightBlue)
                bClear = False
            End If
            o = Me.GetColumnValueAtRow(source, rowNum)
            If (Not (o) Is Nothing) Then
                'Use for alpha
                'Dim c As Char
                'c = CType(o, String).Substring(0, 1)
                Dim c As String
                c = CType(o, String)

                'Use for numeric
                '  o = CInt(o)
                If (o <= 10) Then
                    backBrush = New SolidBrush(Color.White)
                    foreBrush = New SolidBrush(Color.Red)
                    If _row.Contains(rowNum) Then
                        '   backBrush = New LinearGradientBrush(bounds, Color.FromArgb(255, 200, 200), Color.FromArgb(128, 20, 20), LinearGradientMode.BackwardDiagonal)
                        'Blue to Green
                        backBrush = New LinearGradientBrush(bounds, Color.FromArgb(120, 0, 255, 0), Color.FromArgb(120, 0, 0, 255), LinearGradientMode.BackwardDiagonal)
                        ' backBrush = New SolidBrush(Color.Silver)
                        foreBrush = New SolidBrush(Color.Red)
                    End If
                End If
            End If
        Catch ex As Exception
            ' empty catch
        Finally
            ' make sure the base class gets called to do the drawing with
            ' the possibly changed brushes
            MyBase.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight)
            g.FillRectangle(backBrush, bounds)
            Dim vText As String = CType(o, String)
            g.DrawString(vText, Me.TextBox.Font, foreBrush, New RectangleF(bounds.X, bounds.Y, bounds.Width, bounds.Height))
        End Try
    End Sub

End Class

Avatar of matthewsampson
matthewsampson

ASKER

I've been playing with this bit of code from your example:


    Public Sub AccessConnection(ByVal SQL As String)
        Try
            Dim strConnectionString As String
            strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
             "Data Source=Book.mdb;" & "User ID=" & sUSERid & ";" & _
             "Jet OLEDB:Database Password=" & sDBPass
            Dim Con As New System.Data.OleDb.OleDbConnection(strConnectionString)
            myDataAdapter = New System.Data.OleDb.OleDbDataAdapter(SQL, Con)
            Con.Open()
            ' Create and fill dataset
            DS = New DataSet(sTableName)
            myDataAdapter.Fill(DS, sTableName)
            Con.Close()
        Catch Ex As Exception
            MsgBox("Exception: " & Ex.Message & "  " & Ex.ToString, MsgBoxStyle.Critical)
        End Try
    End Sub


I guess I want to replace the bit "Data Source=Book.mdb;"  and replace the book.mdb with a variable that the "OpenFileDialog" throws out.
I don't suppose you know how to do that do you?
Add this...

   Public Sub OpenMDB()
        Dim i As Short
        Dim myOpenFileDialog As New OpenFileDialog
        With myOpenFileDialog
            .CheckFileExists = True
            .DefaultExt = "mdb"
            .Filter = "Access files(*.mdb)|*.mdb"
            .InitialDirectory = "c:\"
            .Multiselect = False
        End With
        ' Use the OpenFileDialog and put the path and name of the selected file in a var.
        If myOpenFileDialog.ShowDialog = DialogResult.OK Then
            sFileName = myOpenFileDialog.FileName
        End If
    End Sub


and in this change...

  Public Sub AccessConnection(ByVal SQL As String)
        Try
            Dim strConnectionString As String
            strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
             "Data Source=" & sFileName & ";" & "User ID=" & sUSERid & ";" & _
             "Jet OLEDB:Database Password=" & sDBPass
            Dim Con As New System.Data.OleDb.OleDbConnection(strConnectionString)
            myDataAdapter = New System.Data.OleDb.OleDbDataAdapter(SQL, Con)
            Con.Open()
            ' Create and fill dataset
            DS = New DataSet(sTableName)
            myDataAdapter.Fill(DS, sTableName)
            Con.Close()
        Catch Ex As Exception
            MsgBox("Exception: " & Ex.Message & "  " & Ex.ToString, MsgBoxStyle.Critical)
        End Try
    End Sub


  Private Sub InitializeDataBase()
        Cursor.Current = Cursors.WaitCursor
        '*********** FOR ADO.NET **********************
        Dim sSQL As String = "SELECT * FROM " & sTableName
     
        OpenMDB()                            '<-----ADD this
        AccessConnection(sSQL)


and the the MODULE you will need to know the table...

 Public sTableName As String = "Contacts"       '<-----????????


How would you go about using the OpenFileDialog if you are using the OleDbConnection, OleDbDataAdapter1, and a Dataset.
To get an idea of it, If you open a new project and then create a new form using the "DataFormWizard", that's what I'm using.

ASKER CERTIFIED SOLUTION
Avatar of Howard Cantrell
Howard Cantrell
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial