DaniWeb IT Discussion Community

Code Snippets (http://www.daniweb.com/code/)
-   vbnet (http://www.daniweb.com/code/vbnet.html)
-   -   Show Data in DataGrid with VB.Net 2003 and SQLServer 2000 (http://www.daniweb.com/code/snippet820.html)

Jx_Man vbnet syntax
Feb 4th, 2008
This Code is easy way to load / show data in Datagrid. This Code write in vb.net 2003 and use sqlserver 2000 as database. I use module to connected VB.Net with SqlServer 2000. so the function to connected can be use in every form in this project.

  1. 'This Code needed one DataGrid On Form.
  2.  
  3.  
  4.  
  5. 'In Module
  6. 'Declare outside of class
  7. Imports System.Data
  8. Imports System.Data.SqlClient
  9.  
  10. Module Koneksi
  11. Public conn As SqlConnection
  12. Public Function GetConnect()
  13. conn = New SqlConnection("server = MyServerName;database = MyDatabaseName;Trusted_Connection = yes")
  14. Return conn
  15. End Function
  16. End Module
  17.  
  18. 'In Form
  19. 'Declare outside of class
  20. Imports System.Data
  21. Imports System.Data.SqlClient
  22.  
  23. 'Procedure To show data in DataGrid
  24. Private Sub ShowDataGrid()
  25. Dim conn As SqlConnection
  26. Dim cmdStudent As New SqlCommand
  27. Dim daStudent As New SqlDataAdapter
  28. Dim dsStudent As New DataSet
  29. Dim dtStudent As New DataTable
  30.  
  31. conn = GetConnect()
  32. Try
  33. cmdStudent = conn.CreateCommand
  34. cmdStudent.CommandText = "SELECT * FROM YourTableName"
  35. daStudent.SelectCommand = cmdStudent
  36. daStudent.Fill(dsStudent, "YourTableName")
  37. dgStudent.DataSource = dsStudent
  38. dgStudent.DataMember = "YourTableName"
  39. dgStudent.ReadOnly = True
  40. Catch ex As Exception
  41. MsgBox("Error: " & ex.Source & ": " & ex.Message, MsgBoxStyle.OKOnly, "Connection Error !!")
  42. End Try
  43. End Sub
  44.  
  45. ' Call procedure ShowDataGrid() on event Form Load
  46. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  47. ShowDataGrid() ' Load data to view in data grid
  48. End Sub
  49. ' You can change the event to call this procedure like in button pressed and etc..