JayBeeOH

Better Data Reader

Jun 10th, 2016
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 8.70 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:   Better 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. The separation of UI and Data
  22. '                 Access Layers are shown in the app.
  23. '
  24. '                 To choose the correct ConnectionString,
  25. '                   see http://www.connectionstrings.com/ .
  26. '
  27. '                 Documentation is at:
  28. '                   App's screen image is at: http://imgur.com/1CijOyT
  29. '                   App's Visual Basic .NET code is at http://pastebin.com/S7mJtk0Q (Original Bare Bones Data Reader)
  30. '                   App's Visual Basic .NET code is at http://pastebin.com/Qm3zCRPY (General Data Reader)
  31. '                   App's Visual Basic .NET code is at http://pastebin.com/cGBPn4xJ (Better Data Reader)  
  32. '                   Video tutorial at YouTube: http://www.youtube.com/user/bolenpresents
  33. '-------------------------------------------------------------------------------------------
  34. 'Note: Add Reference to DAL (Data Access Layer) to this Project.
  35.  
  36. Imports DAL                     ' Data Access Layer
  37. Imports System.Data.OleDb       ' Using a MS Access database
  38.  
  39. Public Class InquiryForm
  40.  
  41.     Private bs As New BindingSource
  42.  
  43.     Private Sub InquiryDGV_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) _
  44.         Handles InquiryDGV.DataError
  45.  
  46.         MessageBox.Show(e.Exception.Message,
  47.                 "Data Error",
  48.                 MessageBoxButtons.OK,
  49.                 MessageBoxIcon.Error)
  50.     End Sub
  51.  
  52.     ' Form Load - Initialization and Housekeeping.
  53.     Private Sub InquiryForm_Load(sender As Object, e As EventArgs) _
  54.         Handles MyBase.Load
  55.  
  56.         ' DataGridView property changes that could be done in the design mode.
  57.         With InquiryDGV
  58.             '.Dock = DockStyle.Fill
  59.             .AllowUserToAddRows = False
  60.             .AllowUserToDeleteRows = False
  61.             .AllowUserToOrderColumns = True
  62.             .AlternatingRowsDefaultCellStyle.BackColor = Color.WhiteSmoke
  63.             .Anchor = (AnchorStyles.Left Or AnchorStyles.Top Or
  64.                 AnchorStyles.Right Or AnchorStyles.Bottom)
  65.             .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells
  66.             .BorderStyle = BorderStyle.Fixed3D
  67.             .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
  68.             .ReadOnly = True
  69.  
  70.             ' DataGridView Column Headers Bold – must be set in run mode.
  71.             .ColumnHeadersDefaultCellStyle.Font =
  72.                 New Font(.ColumnHeadersDefaultCellStyle.Font, FontStyle.Bold)
  73.         End With
  74.  
  75.     End Sub
  76.  
  77.     ' Filter and sort data from the database and display in a datagridview.
  78.     Private Sub SearchToolStripButton_Click(sender As Object, e As EventArgs) _
  79.         Handles SearchToolStripButton.Click
  80.  
  81.         Try
  82.             Dim tb As DataTable = CustomersDB.GetCustomersByLastName(LastNameToolStripTextBox.Text)
  83.  
  84.             If tb.Rows.Count > 0 Then
  85.                 bs.DataSource = tb
  86.                 InquiryDGV.DataSource = bs
  87.             Else
  88.                 MessageBox.Show("Search criteria yielded no records.",
  89.                                             Me.Text,
  90.                                             MessageBoxButtons.OK,
  91.                                             MessageBoxIcon.Information)
  92.             End If
  93.         Catch ex As DataException       ' General ADO.NET Component error.
  94.             MessageBox.Show(ex.Message,
  95.                 ex.GetType.ToString,
  96.                 MessageBoxButtons.OK,
  97.                 MessageBoxIcon.Error)
  98.         Catch ex As OleDbException      ' OleDBException error.
  99.             MessageBox.Show("Database error # 0x" & ex.ErrorCode.ToString("X") & " - " & ex.Message,
  100.                 ex.GetType.ToString,
  101.                 MessageBoxButtons.OK,
  102.                 MessageBoxIcon.Error)
  103.         Catch ex As Exception           ' General catch all error.
  104.             MessageBox.Show(ex.Message,
  105.                  ex.GetType.ToString,
  106.                 MessageBoxButtons.OK,
  107.                 MessageBoxIcon.Error)
  108.         End Try
  109.  
  110.         ' Place cursor back into Textbox for next search.
  111.         LastNameToolStripTextBox.SelectAll()
  112.         LastNameToolStripTextBox.Focus()
  113.  
  114.     End Sub
  115.  
  116. End Class
  117.  
  118. '-------------------------------------------------------------------------------------------
  119. ' Class Name:     CustomersDB
  120. '
  121. ' Author:         Joseph L. Bolen
  122. ' Date Created:   23 MAY 2016
  123. '
  124. ' Description:    For this demonstration, the Customers table from the MS Access
  125. '                 database Northwind is being used. The database's file location
  126. '                 is retrieved from the App.config file using the NorthwindDB class.
  127. '
  128. Imports System.Data.OleDb
  129.  
  130. Public Class CustomersDB
  131.  
  132.     Public Shared Function GetCustomersByLastName(ByVal lName As String) As DataTable
  133.  
  134.         ' Best Practise is to list fields to be selected. NOT THE WILDCARD!
  135.         ' Dim query As String = "SELECT * " &
  136.         Dim query As String = "SELECT Company, [Last Name], [First Name], " &
  137.                                 "[Job Title], [Business Phone], [Fax Number] " &
  138.                             "FROM Customers " &
  139.                             "WHERE [Last Name] Like @p1 " &
  140.                             "ORDER BY [Last Name], [First Name];"
  141.  
  142.         Dim tb As New DataTable
  143.  
  144.         Try
  145.             Using con As OleDbConnection = NorthwindDB.GetConnection()
  146.                 Using cmd As New OleDbCommand(query, con)
  147.                     ' ANSI-89 wildcard character is the asterisk (*).
  148.                     ' ANSI-92 wildcard characters is the percent sign (%).
  149.                     cmd.Parameters.AddWithValue("@p1", lName & "%")
  150.  
  151.                     con.Open()
  152.                     Using rdr As OleDbDataReader = cmd.ExecuteReader
  153.                         tb.Load(rdr)
  154.                     End Using
  155.                 End Using
  156.             End Using
  157.         Catch ex As Exception
  158.             Throw ex
  159.         End Try
  160.  
  161.         Return tb
  162.  
  163.     End Function
  164.  
  165. End Class
  166.  
  167. '-------------------------------------------------------------------------------------------
  168. ' Class Name:     NorthwindDB
  169. '
  170. ' Author:         Joseph L. Bolen
  171. ' Date Created:   23 MAY 2016
  172. '
  173. ' Description:    For this demonstration, the Customers table from the MS Access
  174. '                 database Northwind is being used. The database's file location
  175. '                 is retrieved from the App.config file.
  176. '-------------------------------------------------------------------------------------------
  177.  
  178. 'Note: Add Reference to System.Configuration to the Project.
  179.  
  180. Imports System.Configuration
  181. Imports System.Data.OleDb       ' Using a MS Access database
  182.  
  183. Public Class NorthwindDB
  184.  
  185.     Public Shared Function GetConnection() As OleDbConnection
  186.         Dim conn As String = ConfigurationManager.ConnectionStrings("NorthwindDB").ConnectionString
  187.         Return New OleDbConnection(conn)
  188.     End Function
  189.  
  190. End Class
  191.  
  192. <?xml version="1.0" encoding="utf-8" ?>
  193. <!--
  194.  File Name:      app.config
  195.  
  196.  Author:         Joseph L. Bolen
  197.  Date Created:   23 MAY 2016
  198.  
  199.  Description:    The ConnetionStrings block of coded was added to the file.
  200.                  The named ConnectionString is NorthwindDB.
  201. -->
  202. <configuration>
  203.     <startup>
  204.         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  205.     </startup>
  206.   <connectionStrings>
  207.     <add name="NorthwindDB" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;
  208.         Data Source=U:\Databases\AccessDatabases\Northwind.accdb;
  209.         Persist Security Info=False;"
  210.          providerName="System.Data.Oledb"/>
  211.   </connectionStrings>
  212. </configuration>
Advertisement
Add Comment
Please, Sign In to add comment