Data Access with VB using Visual Studio 2010

About this Tutorial –

Objectives –

Delegates will learn to develop web applications using VB 4.0. After completing this course, delegates will be able to:

  • Use Visual Studio 2010 effectively
  • Data Access with VB using Visual Studio 2010

Audience

This course has been designed primarily for programmers new to the .Net development platform. Delegates experience solely in Windows application development or earlier versions of ASP.Net will also find the content beneficial.

Prerequisites

Before attending this workshop, students must:

  • Be able to manage a solution environment using the Visual Studio 2010 IDE and tools
  • Be able to program an application using a .NET Framework 4.0 compliant language

Contents

Copyright 20/12/12 – David Ringsell

Download Solutions

Java tutorial

Want to know more?
TalkIT provides C# training in Bath, Bristol and around the U.K.

Lab 1 Data Access

Exercise 1

Retrieving data with a Data Reader
In this exercise, you will create a web application to display a list of employees. You will use connection, command, and data reader objects to retrieve data from the Northwind database.

    1. Create a new empty web application project called DataReader:
      • Start Visual Studio 2010.
      • Select the File menu, then New, then Project.
      • Make sure (if you are using the Professional Version) that Visual Basic and then Web is selected at the left of the screen under Installed Templates.
      • Name the project and the solution: DataReader.
      • Browse to the place on your computer where you wish Visual Studio to create the directory for your solution (keeping the tick box selected).
      • Select ASP.NET Web Application.
    2. You will need to create a connection to the Northwind Database:
      • Select Server Explorer (accessed via the View menu).
      • Right-click on ‘Data Connections’ and select ‘Add Connection’.
      • For ‘Data source’ select Microsoft SQL Server (SqlClient).
      • Type in a full stop for the Server name (it will then select the Server Name of the local machine, treating it as the default one).
      • For authentication choose ‘Windows Authentication’.
      • Under ‘Connect to a database’ choose the ‘Select or enter a database name’ option. The Northwind database will then appear in the drop-down list.
      • Finish by clicking ‘Test Connection’ at the bottom to confirm that Visual Studio has successfully connected to the Northwind Database (which is stored within SQL Server 2008).
    3. Add a ListBox control to the default form.
    4. Import the SQLClient namespace in to the class:

Imports System.Data.SqlClient

  1. In the Page Load event, add code to create and open a new SqlConnection. Put a dot in the connection string for Data Source:
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _Handles Me.Load
    'Create and open a connection to Northwind database
    Dim conn As SqlConnection = New SqlConnection("Data Source=.;Initial _ Catalog=Northwind;Integrated Security=TRUE")
    conn.Open()
  2. Create a string to get rows from the Employees table. Use a SQL SELECT statement.
    Dim queryString As String = "SELECT CustomerID, CompanyName FROM dbo.Customers"
  3. Create a command object using the connection and the query string:
  4. Dim com As SqlCommand = New SqlCommand(queryString, conn)
  5. Call the command’s ExecuteReader method and assign the result to a datareader object:
  6. Dim dr As SqlDataReader = com.ExecuteReader()
  7. Iterate through the datareader to add the employee names to the list box. Use a while loop:
  8. While (dr.Read())
    'dr.GetString(1);
    ListBox1.Items.Add(dr("CustomerID").ToString() + " " + _
    dr("CompanyName").ToString())
    End While
  9. Run the application to test if employee data is displayed.
  10. View code file.

Exercise 2

Updating the Database from a Data Set
In this exercise, you will create an application that shows and edits customer data. You will add an update button that writes any changes made to the data back to the database.

    1. Create a new empty web application project called Dataset.
    2. Add a GridView control to the default form.
    3. Import the SQLClient namespace in to the class:

Imports System.Data.SqlClient

    1. Declare at class level these ADO.Net objects:

Private conn As SqlConnection
Private da As SqlDataAdapter
Private ds As DataSet

    1. In the Page Load event add code to create a new connection using this connection string:

"Data Source=.;Initial Catalog=Northwind;Integrated Security=True"

    1. Instantiate the SqlDataAdapter using the connection and this SQL statement:

"SELECT CustomerID, CompanyName FROM dbo.Customers"

    1. Instantiate the data set. Fill the data set using the data adapter with this statement:

da.Fill(ds, "Customers")

    1. Bind the GridView control to the data set.
    2. Run the application to test if customer data is displayed.
    3. Add a button control to the form and change its text property to Update.
    4. Declare at class level a command builder object:

Private cb As SqlCommandBuilder

    1. In the button’s click event add code to instantiate the command builder object using data adapter.
    2. Create an update command and assign it to the data adapter’s update command property:

da.UpdateCommand = cb.GetUpdateCommand()

    1. Update the database using the data adapter’s Update method:

da.Update(ds.Tables("Customers"))

  1. Run the application to test if customer data is updated.
  2. View code file.

Exercise 3

Display data from the Customers table in a Gridview control
In this exercise, you will drag a gridview control on to a web form. You will then configure a datasource control to display rows from the customer table in the gridview.

  1. Create a new empty web application project called GridView.
  2. Add a GridView control to the default form.
  3. Use GridView’s SmartTag to create a new datasource control
  4. Configure the datasource to connect to the Northwind database.
  5. Select the Customers table from the database.
  6. Run the application to test if customer data is shown.

Exercise 4

Calling a Stored Procedure
In this exercise, you will create a web application to display a customer’s order history. You will use connection, command, parameter and data reader objects to retrieve data from the Northwind database. The command will call a stored procedure using the customer’s ID as a parameter.

    1. Create a new empty web application project called CustomerOrders.
    2. Add a Web Form called frmEmployees.
    3. Add a ListBox, Label, TextBox and a button control to the form.
    4. Import the SQLClient namespace in to the class:

Imports System.Data.SqlClient

    1. In the button’s click event, add code to create and open a new connection, using this connection string:

"Data Source=.;Initial Catalog=Northwind;Integrated Security =True"

    1. Create the command object and set its properties:

Dim com As SqlCommand = new SqlCommand()
com.Connection = conn
com.CommandText = "CustOrderHist"
com.CommandType = CommandType.StoredProcedure

    1. Create the parameter object and add it to the command’s parameter collection:

Dim param As SqlParameter = new SqlParameter("@CustomerID",SqlDbType.NVarChar, 5)
param.Value = txtID.Text
com.Parameters.Add(param)

    1. Call the command’s ExecuteReader method and assign the result to a data reader object:

Dim dr As SqlDataReader = com.ExecuteReader()

    1. Iterate through the data reader to add the product names & totals to the list box. Use a while loop:

While (dr.Read())
ListBox1.Items.Add(dr("ProductName") + " " + dr("Total").ToString())
End While

  1. Run the application to test if customer data is displayed; type ‘arout’ into the Customer ID box and click ‘Show Order History’ in order to display the data for that specific customer.
  2. View code file.

Lab 2. Using LINQ to SQL

Exercise 1
Display the Customers table from the Northwind database using a LINQ to SQL Query

  1. Create a new empty web application project called LINQ to SQL.
  2. Add an App_Code folder to the project.
  3. Add a new LINQ to SQL Classes file to the App_Code folder, call this NWind.dbml.
  4. Open Server Explorer, then drag the Customers table to the LINQ to SQL Classes design surface. This will create an object that you can query.
  5. Add a new web form to the project and call this Customers.aspx. Make this the start page.
  6. Add a GridView control to the Customers.aspx designer and call this gvCustomers.
  7. Add code similar to this to create a NWindDataContext and display customers (you may have to adjust the connection string):'Get customers' collection from DataContext
    Dim context As NWindDataContext = new NWindDataContext _
    ("Data Source=.;Initial Catalog=Northwind; _
    Integrated Security=True")

    'Select customers from USA with LINQ query
    Dim custs = From p In dc.Customers Where p.Country = "USA" _
    Select p.CustomerID, p.ContactName, p.CompanyName, p.Country
    'Bind filtered collection to gridview
    this.gvCustomers.DataSource = custs
    this.gvCustomers.DataBind()

Exercise 2
Display a customer’s details when a customer row is selected

  1. Add a DetailsView control to the Customers.aspx designer and call this dvCustomers.
  2. Set the Data Key Name property of the gridview to CustomerID.
  3. Include a select column in the gridview, by selecting Edit Columns after clicking the gridviews smart tag.
  4. Add code similar to this to display a customer’s details (you may have to adjust the connection string:Protected Sub gvCustomers_SelectedIndexChanged(ByVal sender As _
    Object, ByVal e As EventArgs)
    'Get customer object from selected row
    Dim cust = dc.Customers.Where(Function(p) p.CustomerID = _
    gvCustomers.SelectedValue.ToString())
    'Bind filtered collection to detailview
    dvCustomers.DataSource = cust
    dvCustomers.DataBind()
    End Sub
  5. View code file.

Back to the beginning

If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top