JayBeeOH

DataReader On Join Demo

Nov 10th, 2016
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 7.04 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:   DataReader On Join Demo
  13. '
  14. ' Author:         Joseph L. Bolen
  15. ' Date Created:   10 NOV 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 Orders table from the MS SQL Express
  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 Visual Basic .NET code is at http://pastebin.com/WZ4uWk81
  29. '-------------------------------------------------------------------------------------------
  30. 'Note: Add Reference to DAL (Data Access Layer) to this Project.
  31.  
  32. Imports DAL
  33. Imports System.Data.SqlClient
  34.  
  35. Public Class InquiryForm
  36.  
  37.     Private bs As New BindingSource
  38.  
  39.     Private Sub InquiryForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  40.  
  41.         OrderDateDTP.CustomFormat = "MM/yyyy"
  42.         OrderDateDTP.Format = DateTimePickerFormat.Custom
  43.  
  44.         ' DataGridView property changes that could be done in the design mode.
  45.         With InquiryDGV
  46.             '.Dock = DockStyle.Fill
  47.             .AllowUserToAddRows = False
  48.             .AllowUserToDeleteRows = False
  49.             .AllowUserToOrderColumns = True
  50.             .AlternatingRowsDefaultCellStyle.BackColor = Color.WhiteSmoke
  51.             .Anchor = (AnchorStyles.Left Or AnchorStyles.Top Or
  52.                 AnchorStyles.Right Or AnchorStyles.Bottom)
  53.             .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells
  54.             .BorderStyle = BorderStyle.Fixed3D
  55.             .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
  56.             .ReadOnly = True
  57.  
  58.             ' DataGridView Column Headers Bold – must be set in run mode.
  59.             .ColumnHeadersDefaultCellStyle.Font =
  60.                 New Font(.ColumnHeadersDefaultCellStyle.Font, FontStyle.Bold)
  61.         End With
  62.  
  63.     End Sub
  64.  
  65.     ' Filter and sort data from the database and display in a datagridview.
  66.  
  67.     Private Sub SearchButton_Click(sender As Object, e As EventArgs) _
  68.         Handles SearchButton.Click
  69.  
  70.         Try
  71.             Dim tb As DataTable = OrdersDB.GetOrdersByDate(OrderDateDTP.Value)
  72.  
  73.             If tb.Rows.Count > 0 Then
  74.                 bs.DataSource = tb
  75.                 InquiryDGV.DataSource = bs
  76.             Else
  77.                 MessageBox.Show("Search criteria yielded no records.",
  78.                                 Me.Text,
  79.                                 MessageBoxButtons.OK,
  80.                                 MessageBoxIcon.Information)
  81.             End If
  82.         Catch ex As DataException       ' General ADO.NET Component error.
  83.             MessageBox.Show(ex.Message,
  84.                 ex.GetType.ToString,
  85.                 MessageBoxButtons.OK,
  86.                 MessageBoxIcon.Error)
  87.         Catch ex As SqlException      ' SQLException error.
  88.             MessageBox.Show("Database error # 0x" & ex.ErrorCode.ToString("X") & " - " & ex.Message,
  89.                 ex.GetType.ToString,
  90.                 MessageBoxButtons.OK,
  91.                 MessageBoxIcon.Error)
  92.         Catch ex As Exception           ' General catch all error.
  93.             MessageBox.Show(ex.Message,
  94.                  ex.GetType.ToString,
  95.                 MessageBoxButtons.OK,
  96.                 MessageBoxIcon.Error)
  97.         End Try
  98.  
  99.         ' Place cursor backfor next search.
  100.  
  101.         OrderDateDTP.Focus()
  102.     End Sub
  103. End Class
  104.  
  105. '======================================================================================================
  106.  
  107. The App.Config file ...
  108.  
  109. <?xml version="1.0" encoding="utf-8" ?>
  110. <configuration>
  111.     <startup>
  112.         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
  113.     </startup>
  114.   <connectionStrings>
  115.     <add name="NorthwindDB" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True;" providerName="System.Data.SQLClient"/>
  116.   </connectionStrings>
  117. </configuration>
  118.  
  119. '======================================================================================================
  120. ' In the DAL project...
  121.  
  122. Imports System.Data.SqlClient
  123. Imports System.Configuration
  124.  
  125. Public Class NorthwindDB
  126.  
  127.     Public Shared Function GetConnection() As SqlConnection
  128.         Dim conn As String = ConfigurationManager.ConnectionStrings("NorthwindDB").ConnectionString
  129.         Return New SqlConnection(conn)
  130.     End Function
  131. End Class
  132.  
  133. '======================================================================================================
  134.  
  135.  
  136. Imports System.Data.SqlClient
  137.  
  138. Public Class OrdersDB
  139.  
  140.     Public Shared Function GetOrdersByDate(ByVal selectionDate As Date) As DataTable
  141.  
  142.         ' Best Practise is to list fields to be selected. NOT THE WILDCARD!
  143.  
  144.         Dim query As String = "SELECT C.CustomerID, C.CompanyName, O.OrderID,  O.OrderDate " &
  145.                               "FROM Orders As O " &
  146.                               "INNER JOIN Customers As C " &
  147.                               "ON O.CustomerID=C.CustomerID " &
  148.                               "WHERE DATEPART(yyyy,O.OrderDate) = @yyyyOrderDate AND DATEPART(mm,O.OrderDate) = @mmOrderDate " &
  149.                               "ORDER BY C.CompanyName;"
  150.         Dim tb As New DataTable
  151.  
  152.         Try
  153.             Using con As SqlConnection = NorthwindDB.GetConnection()
  154.                 Using cmd As New SqlCommand(query, con)
  155.                     ' ANSI-89 wildcard character is the asterisk (*).
  156.                     ' ANSI-92 wildcard characters is the percent sign (%).
  157.                     cmd.Parameters.AddWithValue("@yyyyOrderDate", selectionDate.ToString("yyyy"))
  158.                     cmd.Parameters.AddWithValue("@mmOrderDate", selectionDate.ToString("MM"))
  159.  
  160.                     con.Open()
  161.                     Using rdr As SqlDataReader = cmd.ExecuteReader
  162.                         tb.Load(rdr)
  163.                     End Using
  164.                 End Using
  165.             End Using
  166.  
  167.         Catch ex As Exception
  168.             Throw ex
  169.         End Try
  170.  
  171.         Return tb
  172.  
  173.     End Function
  174.  
  175. End Class
Advertisement
Add Comment
Please, Sign In to add comment