Tuesday, August 27, 2013

Getting all the records from a table and displaying them in a DataGridView (Visual Basic.Net Version)

Written by: Biniam Asnake


Assuming you have already took the pleasure of creating a Visual Basic Windows Application and you have a database in SQL Server. For this case let’s call the database “Industry”


1st. Create app.config file (By right clicking on your project’s name in Solution Explorer)
2nd. Paste the following code


<connectionStrings>
   <add name="connectionString"
       connectionString="SERVER=(local);; DATABASE = Industry; Integrated Security=True;
Trusted_Connection= Yes;"
       providerName="System.Data.SqlClient" />
</connectionStrings>




3rd. In the code view of your from where you put your DataGridView, add the following code.

ASSUMPTIONS
The name of the form is: frmDisplay
The name of the DataGridView is:gvSearch
The name of the Button is:btnSearchGo
The name of the table you want to search from is: tblMyTable


Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration


Public Class frmDisplay


   Dim connectionString As String = String.Empty


   Sub New()


       ' This call is required by the designer.
       InitializeComponent()


       ' Add any initialization after the InitializeComponent() call.
Me.connectionString =
ConfigurationManager.ConnectionStrings("connectionString").ConnectionString


   End Sub
Private Sub btnSearchGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearchGo.Click


           Dim selectDataAdaptor As New SqlDataAdapter
           selectDataAdaptor.SelectCommand = New SqlCommand


           selectDataAdaptor.SelectCommand.Connection = New SqlConnection(connectionString)


           selectDataAdaptor.SelectCommand.CommandText = _
                       "SELECT * " & _
                       "FROM tblMyTable " & _


           Dim objDataSet As New DataSet


           selectDataAdaptor.Fill(objDataSet, "Search")
           selectDataAdaptor.AcceptChangesDuringFill = True


           gvSearch.DataSource = objDataSet
           gvSearch.DataMember = "Search"
           gvSearch.AllowUserToResizeColumns = True
gvSearch.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader


   End Sub





No comments:

Post a Comment