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
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
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.OL EDB.4.0;" & _
"Data Source=Book.mdb;" & "User ID=" & sUSERid & ";" & _
"Jet OLEDB:Database Password=" & sDBPass
Dim Con As New System.Data.OleDb.OleDbCon nection(st rConnectio nString)
myDataAdapter = New System.Data.OleDb.OleDbDat aAdapter(S QL, 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?
Public Sub AccessConnection(ByVal SQL As String)
Try
Dim strConnectionString As String
strConnectionString = "Provider=Microsoft.Jet.OL
"Data Source=Book.mdb;" & "User ID=" & sUSERid & ";" & _
"Jet OLEDB:Database Password=" & sDBPass
Dim Con As New System.Data.OleDb.OleDbCon
myDataAdapter = New System.Data.OleDb.OleDbDat
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.ShowDialo g = 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.OL EDB.4.0;" & _
"Data Source=" & sFileName & ";" & "User ID=" & sUSERid & ";" & _
"Jet OLEDB:Database Password=" & sDBPass
Dim Con As New System.Data.OleDb.OleDbCon nection(st rConnectio nString)
myDataAdapter = New System.Data.OleDb.OleDbDat aAdapter(S QL, 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" '<-----????????
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.ShowDialo
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.OL
"Data Source=" & sFileName & ";" & "User ID=" & sUSERid & ";" & _
"Jet OLEDB:Database Password=" & sDBPass
Dim Con As New System.Data.OleDb.OleDbCon
myDataAdapter = New System.Data.OleDb.OleDbDat
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" '<-----????????
ASKER
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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
'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.ICon
'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.DataG
Friend WithEvents cmdExit As System.Windows.Forms.Butto
Friend WithEvents cmdOk As System.Windows.Forms.Butto
Friend WithEvents cmdAdd As System.Windows.Forms.Butto
Friend WithEvents cmdDelete As System.Windows.Forms.Butto
Friend WithEvents cmdUpdate As System.Windows.Forms.Butto
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.TextB
Friend WithEvents txtDescription As System.Windows.Forms.TextB
Friend WithEvents ToolTip As System.Windows.Forms.ToolT
<System.Diagnostics.Debugg
Me.components = New System.ComponentModel.Cont
Me.dgInventory = New System.Windows.Forms.DataG
Me.cmdExit = New System.Windows.Forms.Butto
Me.cmdOk = New System.Windows.Forms.Butto
Me.cmdAdd = New System.Windows.Forms.Butto
Me.cmdDelete = New System.Windows.Forms.Butto
Me.cmdUpdate = New System.Windows.Forms.Butto
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.TextB
Me.txtDescription = New System.Windows.Forms.TextB
Me.ToolTip = New System.Windows.Forms.ToolT
CType(Me.dgInventory, System.ComponentModel.ISup
Me.SuspendLayout()
'
'dgInventory
'
Me.dgInventory.CaptionVisi
Me.dgInventory.DataMember = ""
Me.dgInventory.HeaderForeC
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("Micro
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("Micro
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("Micro
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("Micro
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("Micro
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
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("Micro
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("Micro
Me.lblDescription.Location
Me.lblDescription.Name = "lblDescription"
Me.lblDescription.Size = New System.Drawing.Size(76, 16)
Me.lblDescription.TabIndex
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
Me.txtDescription.Name = "txtDescription"
Me.txtDescription.ReadOnly
Me.txtDescription.Size = New System.Drawing.Size(336, 20)
Me.txtDescription.TabIndex
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.txtDesc
Me.Controls.Add(Me.txtQty)
Me.Controls.Add(Me.lblDesc
Me.Controls.Add(Me.lblQty)
Me.Controls.Add(Me.lblTabl
Me.Controls.Add(Me.cmdUpda
Me.Controls.Add(Me.cmdDele
Me.Controls.Add(Me.cmdAdd)
Me.Controls.Add(Me.cmdOk)
Me.Controls.Add(Me.cmdExit
Me.Controls.Add(Me.dgInven
Me.MaximizeBox = False
Me.Name = "frmComBuilder"
Me.StartPosition = System.Windows.Forms.FormS
Me.Text = "frmEditInventory"
CType(Me.dgInventory, System.ComponentModel.ISup
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.OleDbCom
' 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.Comman
cb = New System.Data.OleDb.OleDbCom
Dim mystr As String = cb.GetUpdateCommand.Comman
Dim val As Integer = cb.GetUpdateCommand.Parame
' Bind DataGrid control to this dataset
dgInventory.SetDataBinding
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.TextC
'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.TextC
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.GridColumnS
(New DataGridColumnStyle() {grdColStyle1, grdColStyle2, grdColStyle3, grdColStyle4})
dgInventory.TableStyles.Ad
' dgInventory.ReadOnly = True
dgInventory.Select(0)
txtQty.Text = dgInventory.Item(dgInvento
txtDescription.Text = dgInventory.Item(dgInvento
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).Colu
ds.Tables(sTableName).Prim
'********* Use this for single edit mode **************
'CurRow = DS.Tables("Inventory_" & sTableName).Rows.Find(dgIn
'CurRow.BeginEdit()
'CurRow("OnHand") = dgInventory.Item(dgInvento
'CurRow("Description") = dgInventory.Item(dgInvento
'CurRow.EndEdit()
'MsgBox("Record edited successfully")
'CurRow.AcceptChanges()
'myDataAdapter.Update(DS.T
'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.Ta
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
' "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
'DS.Tables(sTableName).Row
'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
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
Dim dgcc As DataGridCell = Me.dgInventory.CurrentCell
Dim tb As TextBox = GetEmbeddedTextBox(dgcc.Co
If Not (tb Is Nothing) Then
Dim oldValue As String = Me.dgInventory(dgcc).ToStr
Dim newValue As String = tb.Text
If newValue <> oldValue Then
GetEmbeddedDGTextBox(dgcc.
End If
End If
End Sub
Private Function GetEmbeddedTextBox(ByVal col As Integer) As TextBox
Dim tbc As DataGridTextBoxColumn = Me.dgInventory.TableStyles
If Not (tbc Is Nothing) AndAlso tbc.TextBox.Modified Then
Return tbc.TextBox
End If
Return Nothing
End Function
Private Function GetEmbeddedDGTextBox(ByVal
Dim tbc As DGColorTextBox = Me.dgInventory.TableStyles
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.Mouse
Try
txtQty.Text = dgInventory.Item(dgInvento
txtDescription.Text = dgInventory.Item(dgInvento
'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.DataG
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.DataG
Console.WriteLine("You clicked the background.")
Case System.Windows.Forms.DataG
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.DataG
Console.WriteLine("You clicked the column header for column " & hti.Column)
Case System.Windows.Forms.DataG
Console.WriteLine("You clicked the row header for row " & hti.Row)
Case System.Windows.Forms.DataG
Console.WriteLine("You clicked the column resizer for column " & hti.Column)
Case System.Windows.Forms.DataG
Console.WriteLine("You clicked the row resizer for row " & hti.Row)
Case System.Windows.Forms.DataG
Console.WriteLine("You clicked the caption")
Case System.Windows.Forms.DataG
Console.WriteLine("You clicked the parent row")
End Select
End Sub
Private Sub dgInventory_MouseMove(ByVa
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.DataG
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(dgInven
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
' Set the Position to the Row.
myCurrencyManager.Position
' Get the clicked DataGridTextBoxColumn.
Dim gridCol As DGColorTextBox = CType(dgt.GridColumnStyles
' Invoke the GetColumnValueAtRow.
Return oCellValue = gridCol.GetColValueAtRow(m
End If
End Function
#End Region
#Region "Keypress and Validating"
Private Sub txtQty_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.Canc
dgInventory.Item(dgInvento
dgInventory.Item(dgInvento
End Sub
Private Sub txtQty_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPr
Dim KeyAscii As Short = Asc(e.KeyChar)
Select Case KeyAscii
Case System.Windows.Forms.Keys.
KeyAscii = 0
Case Keys.Enter, Keys.Tab 'same as 13
dgInventory.Item(dgInvento
dgInventory.Item(dgInvento
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(By
Dim KeyAscii As Short = Asc(e.KeyChar)
Select Case KeyAscii
Case System.Windows.Forms.Keys.
KeyAscii = 0
Case Keys.Enter, Keys.Tab 'same as 13
dgInventory.Item(dgInvento
dgInventory.Item(dgInvento
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(dgInvento
txtDescription.Text = dgInventory.Item(dgInvento
Case Keys.Right, Keys.Left, Keys.Down, Keys.Up, Keys.Tab
txtQty.Text = dgInventory.Item(dgInvento
txtDescription.Text = dgInventory.Item(dgInvento
'dgInventory.Item(dgInvent
'dgInventory.Item(dgInvent
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.GetCellBoun
rect = New Rectangle(rect.Right, rect.Top, Me.dgInventory.Width, rect.Height)
Me.dgInventory.Invalidate(
End Sub 'RefreshRow
Private Sub ResetGridColor()
grdColStyle2.ClearGridColo
grdColStyle3.ClearGridColo
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.GetCurrentDirect
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.OL
"Data Source=Book.mdb;" & "User ID=" & sUSERid & ";" & _
"Jet OLEDB:Database Password=" & sDBPass
Dim Con As New System.Data.OleDb.OleDbCon
myDataAdapter = New System.Data.OleDb.OleDbDat
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.ArrayLi
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
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,
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
'Blue to Green
backBrush = New LinearGradientBrush(bounds
' backBrush = New SolidBrush(Color.Silver)
foreBrush = New SolidBrush(Color.White)
End If
If bClear = True Then
backBrush = New SolidBrush(Color.GhostWhit
foreBrush = New SolidBrush(Color.MidnightB
bClear = False
End If
o = Me.GetColumnValueAtRow(sou
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
'Blue to Green
backBrush = New LinearGradientBrush(bounds
' 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,
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