JayBeeOH

General Data Reader

May 23rd, 2016
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 7.96 KB | None | 0 0
  1. '------------------------------------------------------------------------------------------
  2. '           Notice of My Copyright and Intellectual Property Rights
  3. '
  4. ' Any intellectual property contained within the program by Joseph L. Bolen remains the
  5. ' intellectual property of the Joseph L. Bolen. This means that no person may distribute,
  6. ' publish or provide such intellectual property to any other person or entity for any
  7. ' reason, commercial or otherwise, without the express written permission of Joseph L. Bolen.
  8. '
  9. '                 Copyright © 2016. All rights reserved.
  10. '        All trademarks remain the property of their respective owners.
  11. '-------------------------------------------------------------------------------------------
  12. ' Program Name:   General Data Reader
  13. '
  14. ' Author:         Joseph L. Bolen
  15. ' Date Created:   23 MAY 2016
  16. '
  17. ' Description:    This database inquiry uses the DataReader to quickly
  18. '                 retrieve records from a table and display them in a datagridview.
  19. '                 For this demonstration, the Customers table from the MS Access
  20. '                 database Northwind is being used. The database's file location
  21. '                 is retrieved from the App.config file.
  22. '
  23. '                 To choose the correct ConnectionString,
  24. '                   see http://www.connectionstrings.com/ .
  25. '
  26. '                 Documentation is at:
  27. '                   App's screen image is at: http://imgur.com/dQEpAZt
  28. '                   App's Visual Basic .NET code is at http://pastebin.com/S7mJtk0Q (Original BareBonesDataReader)
  29. '                   App's Visual Basic .NET code is at http://pastebin.com/Qm3zCRPY
  30. '                   Video tutorial at YouTube: http://www.youtube.com/user/bolenpresents
  31. '-------------------------------------------------------------------------------------------
  32. 'Note: Add Reference to DAL (Data Access Layer) to this Project.
  33.  
  34. Imports DAL
  35. Imports System.Data.OleDb       ' Using a MS Access database
  36.  
  37. Public Class InquiryForm
  38.  
  39.     ' Normally, the ConnectionString is retrieved from the App.config file.
  40.     'Const CONN_STRING As String = "Provider=Microsoft.ACE.OLEDB.12.0;" &
  41.     '                        "Data Source=U:\Databases\AccessDatabases\Northwind.accdb;" &
  42.     '                        "Persist Security Info=False;"
  43.  
  44.     Private bs As New BindingSource
  45.  
  46.     Private Sub InquiryDGV_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) _
  47.         Handles InquiryDGV.DataError
  48.  
  49.         MessageBox.Show(e.Exception.Message,
  50.                 "Data Error",
  51.                 MessageBoxButtons.OK,
  52.                 MessageBoxIcon.Error)
  53.     End Sub
  54.  
  55.     ' Form Load - Initialization and Housekeeping.
  56.     Private Sub InquiryForm_Load(sender As Object, e As EventArgs) _
  57.         Handles MyBase.Load
  58.  
  59.         ' DataGridView property changes that could be done in the design mode.
  60.         With InquiryDGV
  61.             '.Dock = DockStyle.Fill
  62.             .AllowUserToAddRows = False
  63.             .AllowUserToDeleteRows = False
  64.             .AllowUserToOrderColumns = True
  65.             .AlternatingRowsDefaultCellStyle.BackColor = Color.WhiteSmoke
  66.             .Anchor = (AnchorStyles.Left Or AnchorStyles.Top Or
  67.                 AnchorStyles.Right Or AnchorStyles.Bottom)
  68.             .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells
  69.             .BorderStyle = BorderStyle.Fixed3D
  70.             .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
  71.             .ReadOnly = True
  72.  
  73.             ' DataGridView Column Headers Bold – must be set in run mode.
  74.             .ColumnHeadersDefaultCellStyle.Font =
  75.                 New Font(.ColumnHeadersDefaultCellStyle.Font, FontStyle.Bold)
  76.         End With
  77.  
  78.     End Sub
  79.  
  80.     ' Filter and sort data from the database and display in a datagridview.
  81.     Private Sub SearchToolStripButton_Click(sender As Object, e As EventArgs) _
  82.         Handles SearchToolStripButton.Click
  83.  
  84.         ' Best Practise is to list fields to be selected. NOT THE WILDCARD!
  85.         ' Dim query As String = "SELECT * " &
  86.         Dim query As String = "SELECT Company, [Last Name], [First Name], " &
  87.                                     "[Job Title], [Business Phone], [Fax Number] " &
  88.                                 "FROM Customers " &
  89.                                 "WHERE [Last Name] Like @p1 " &
  90.                                 "ORDER BY [Last Name], [First Name];"
  91.  
  92.         Try
  93.             Using con As OleDbConnection = NorthwindDB.GetConnection()
  94.                 Using cmd As New OleDbCommand(query, con)
  95.                     ' ANSI-89 wildcard character is the asterisk (*).
  96.                     ' ANSI-92 wildcard characters is the percent sign (%).
  97.                     cmd.Parameters.AddWithValue("@p1", LastNameToolStripTextBox.Text & "%")
  98.  
  99.                     con.Open()
  100.                     Using rdr As OleDbDataReader = cmd.ExecuteReader
  101.                         If rdr.HasRows Then
  102.                             bs.DataSource = rdr
  103.                             InquiryDGV.DataSource = bs
  104.                         Else
  105.                             MessageBox.Show("Search criteria yielded no records.",
  106.                                             Me.Text,
  107.                                             MessageBoxButtons.OK,
  108.                                             MessageBoxIcon.Information)
  109.                         End If
  110.                     End Using
  111.                 End Using
  112.             End Using
  113.         Catch ex As DataException       ' General ADO.NET Component error.
  114.             MessageBox.Show(ex.Message,
  115.                 ex.GetType.ToString,
  116.                 MessageBoxButtons.OK,
  117.                 MessageBoxIcon.Error)
  118.         Catch ex As OleDbException      ' OleDBException error.
  119.             MessageBox.Show("Database error # 0x" & ex.ErrorCode.ToString("X") & " - " & ex.Message,
  120.                 ex.GetType.ToString,
  121.                 MessageBoxButtons.OK,
  122.                 MessageBoxIcon.Error)
  123.         Catch ex As Exception           ' General catch all error.
  124.             MessageBox.Show(ex.Message,
  125.                  ex.GetType.ToString,
  126.                 MessageBoxButtons.OK,
  127.                 MessageBoxIcon.Error)
  128.         End Try
  129.  
  130.         ' Place cursor back into Textbox for next search.
  131.         LastNameToolStripTextBox.SelectAll()
  132.         LastNameToolStripTextBox.Focus()
  133.  
  134.     End Sub
  135.  
  136. End Class
  137.  
  138. '-------------------------------------------------------------------------------------------
  139. ' Class Name:     NorthwindDB
  140. '
  141. ' Author:         Joseph L. Bolen
  142. ' Date Created:   23 MAY 2016
  143. '
  144. ' Description:    For this demonstration, the Customers table from the MS Access
  145. '                 database Northwind is being used. The database's file location
  146. '                 is retrieved from the App.config file.
  147. '-------------------------------------------------------------------------------------------
  148.  
  149. 'Note: Add Reference to System.Configuration to the Project.
  150.  
  151. Imports System.Configuration
  152. Imports System.Data.OleDb       ' Using a MS Access database
  153.  
  154. Public Class NorthwindDB
  155.  
  156.     Public Shared Function GetConnection() As OleDbConnection
  157.         Dim conn As String = ConfigurationManager.ConnectionStrings("NorthwindDB").ConnectionString
  158.         Return New OleDbConnection(conn)
  159.     End Function
  160.  
  161. End Class
  162.  
  163. <?xml version="1.0" encoding="utf-8" ?>
  164. <!--
  165.  File Name:      app.config
  166.  
  167.  Author:         Joseph L. Bolen
  168.  Date Created:   23 MAY 2016
  169.  
  170.  Description:    The ConnetionStrings block of coded was added to the file.
  171.                  The named ConnectionString is NorthwindDB.
  172. -->
  173. <configuration>
  174.     <startup>
  175.         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  176.     </startup>
  177.   <connectionStrings>
  178.     <add name="NorthwindDB" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;
  179.         Data Source=U:\Databases\AccessDatabases\Northwind.accdb;
  180.         Persist Security Info=False;"
  181.          providerName="System.Data.Oledb"/>
  182.   </connectionStrings>
  183. </configuration>
Advertisement
Add Comment
Please, Sign In to add comment