One of the most common ways to display data from a database is with the use of a GridView control. In this tutorial, you will learn how to use a GridView to display data from a database in Visual Basic.

Setup


If you have not already done so, open Visual Studio and create a new web project, unless you are applying concepts from the tutorial in your own project, in which you can ignore this step.

We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.

The Concept…


The GridView Control is used to display data in a tabular fashion within ASP.NET. The output is converted into a HTML table for display in a browser. The control makes it easy for us to display data from a Data Source using ASP.NET. This tutorial will show how we can use the GridView Control to display data easily without the huge amounts of code. 
In this example we will use the GridView with a SqlDataSource and a sample database. We can start off by dragging a GridView onto our page from the Data toolbox in Visual Studio (or Web Developer). We can also drag on a SqlDataSource control.

Step one.


The first step we will take is making our database. We simply need a three column database in which we list out a minimum of 6 to 7 people with their personID, name, and city. personID is set to identity incrementing by 1. Refer to the image below: 



You can now insert data into your table either by query or by inserting it directly to the table.

Step two.


Now that we have a database set up, let us go ahead and develop our default.aspx page. Select the SqlDataSource control from the toolbox and choose Configure Data Source. From the dropdown menu, we will choose the database we wish to connect to, and then press next. If the database is not in the list, we can choose New Connection and configure it from there. This will create the connection string to our web.config file necessary for us to access our database. 

Yes, it is possible to find a good web host. Sometimes it takes a while to find one you are comfortable with. After trying several, we went with Server Intellect and have been very happy thus far. They are by far the most professional, customer service friendly and technically knowledgeable host we’ve found so far.

Next drag and drop a GridView control onto the screen and configure it to the SqlDataSource we just placed and connected to the database. Refresh schema and enable selection, although we are not doing anything that requires selection, this will show you that you can make your GridView present just about any data in any way you want.

The code for the default.aspx page is as follows:
Code Block
Default.aspx
<div>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        SelectCommand="SELECT [name], [city] FROM [Table1]"></asp:SqlDataSource>
    <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource"
        Width="211px">
        <Columns>
            <asp:CommandField ShowSelectButton="True" />
            <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
            <asp:BoundField DataField="city" HeaderText="city" SortExpression="city" />
        </Columns>
    </asp:GridView>
</div>

Step three.


In order to have some functionality to show the interaction with the data, we will double click on the gridview in order for the SelectedIndexChanged event to appear in the code behind. We will need for the label to print out the candidate number of the person selected upon the click of the select link. The code for the code behind is as follows: 
Code Block
Default.aspx.vb

Imports System.Data.SqlClient
 
Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs)
Try
Dim cmd As New SqlCommand("SELECT* TOP 5 name,city FROM Table1"New SqlConnection("Server=localhost;Database=Database;Trusted_Connection=True;"))
 
cmd.Connection.Open()
 
Dim datareader As SqlDataReader = cmd.ExecuteReader()
GridView1.DataSource = datareader

 
GridView1.DataBind()
 
cmd.Connection.Close()
cmd.Connection.Dispose()
 
'You may place an exception here 
'Label1.Text = ex.Message;
Catch ex As Exception
End Try
'GridView1.SelectedIndexChanged += New EventHandler(GridView1_SelectedIndexChanged) //C# EventHandler
AddHandler GridView1.SelectedIndexChanged, AddressOf Me.GridView1_SelectedIndexChanged
 
End Sub
 
Protected Sub GridView1_SelectedIndexChanged(ByVal sender As ObjectByVal e As EventArgs)
 
Label1.Text += GridView1.SelectedIndex.ToString()
 
If GridView1.SelectedIndex <> -1 Then
If GridView1.SelectedIndex = -1 Then
Label1.Text = "Please select the candidate of your choice..."
Else
Dim person As Integer = GridView1.SelectedIndex + 1
 
Label1.Text = "You have selected candidate number " + CType(person, String)
End If
End If
 
End Sub
End Class

Once the person is selected, the label prints out “You have selected candidate number #” where the pound sign stands for the number of the individual. Otherwise, if there is no person selected, the system evaluates it as negative one which will then print out the message, “Please select the candidate of your choice…”.

The end result will appear like the following, we selected Dan Man.

Need help with cloud hosting? Try Server Intellect. We used them for our cloud hosting services and we are very happy with the results! 

A Few Last Words…

Learning how to control and manipulate databases is easy with ASP.NET and we intend to be there every step of the way to help! Thank you for being a valued reader and join us next time for additional database tutorials!