Programming with ADO.NET

Similar documents
Chapter 3. Windows Database Applications The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

VS2010 C# Programming - DB intro 1

CSC 330 Object-Oriented

Chapter 10. Database Applications The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies. Objectives (1 of 2)

Introduction to using Visual Studio 2010 to build data-aware applications

Windows Database Applications

Building Datacentric Applications

How to use data sources with databases (part 1)

Data Binding. Data Binding

Chapter 4. Windows Database Using Related Tables The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Tackle Complex Data Binding in WinForms 2.0

Index. AutoNumber data types, 154 6, 168 and Number data type, 181 AutoPostBack Property, 505, 511, 513 5, 527 8, AVG, 242, 247 8

Data Binding with Windows Forms 2.0

Access Review. 4. Save the table by clicking the Save icon in the Quick Access Toolbar or by pulling

Windows Database Updates

Creating a Crosstab Query in Design View

ADO.NET 2.0. database programming with

Microsoft Access 2010

Microsoft Access 2013

Microsoft Access 2013

Microsoft Visual C# 2005: Developing Applications Table of Contents

ArtOfTest Inc. Automation Design Canvas 2.0 Beta Quick-Start Guide

Course Outline. Writing Reports with Report Builder and SSRS Level 1 Course 55123: 2 days Instructor Led. About this course

How to work with data sources and datasets

About the Authors Introduction p. 1 Exploring Application Architectures p. 9 Introduction p. 9 Choosing the "Right" Architecture p.

Report Designer Report Types Table Report Multi-Column Report Label Report Parameterized Report Cross-Tab Report Drill-Down Report Chart with Static

CIS 209 Final Exam. 1. A Public Property procedure creates a property that is visible to any application that contains an instance of the class.

Writing Reports with Report Designer and SSRS 2014 Level 1

The following instructions cover how to edit an existing report in IBM Cognos Analytics.

Toolkit Activity Installation and Registration

Application Aspect. Hierarchical DataGridView v1.7 BOOKLET

DEVELOPING DATABASE APPLICATIONS (INTERMEDIATE MICROSOFT ACCESS, X405.5)

SQL Server 2005: Reporting Services

Searching and Favorites in Datatel Web UI 4.3

Simple sets of data can be expressed in a simple table, much like a

Module 4: Creating Content Lesson 5: Creating Visualizations Try Now!

ComponentOne Data Source for Entity Framework 1

Chapter 5: Hierarchical Form Lab

Student Manual. Cognos Analytics

Supporting Non-Standard Development Configurations

Volume CREATIVE DATA TECHNOLOGIES, INC. DATALAYER.NET. Getting Started Guide

To complete this database, you will need the following file:

CartêGraph Training Navigator

SOFTWARE SKILLS BUILDERS

Switchboard. Creating and Running a Navigation Form

Enforce Referential. dialog box, click to mark the. Enforce Referential. Integrity, Cascade Update Related Fields, and. Cascade Delete Related

Introduction. Mail Merge. Word 2010 Using Mail Merge. Video: Using Mail Merge in Word To Use Mail Merge: Page 1

Telerik Corp. Test Studio Standalone & Visual Studio Plug-In Quick-Start Guide

A filter that contains elements compatible with the query or view and that is associated with the report.

1. A Web Form created in Visual Basic can only be displayed in Internet Explorer. True False

Custom Reference Data Tables

SPARK. User Manual Ver ITLAQ Technologies

Introduction to Microsoft Access 2016

Kendo UI. Builder by Progress : What's New

CA ERwin Data Modeler

Navigate to Cognos Cognos Analytics supports all browsers with the exception of Microsoft Edge.

Desktop Studio: Sub-reports

erwin Data Modeler Implementation Guide Release 9.8

Creating a Custom Report

Designing SQL Server 2012 Analysis Services Cubes using Samsclub_Star Dataset

Working with Attributes

Colleague UI4.3 Documentation

PowerSchool Handbook Federal Survey Form Report

Attaching Codesoft 6 to an ODBC Database

2015 OSIsoft TechCon. Building Displays with the new PI ProcessBook and PI Coresight

Getting Started With the Cisco PAM Desktop Software

DATABASES 1.0 INTRODUCTION 1.1 OBJECTIVES

PST for Outlook Admin Guide

Working with Macros. Creating a Macro

Working with Excel CHAPTER 1

Chapter 4: Single Table Form Lab

Database Tutorials

Microsoft Access 2013

Working with Excel involves two basic tasks: building a spreadsheet and then manipulating the

To complete this database, you will need the following file:

Filtering Data in SAS Enterprise Guide

Chapter 18 Outputting Data

Objective 1: Familiarize yourself with basic database terms and definitions. Objective 2: Familiarize yourself with the Access environment.

1. Right-click the worksheet tab you want to rename. The worksheet menu appears. 2. Select Rename.

Project 7: Northwind Traders Order Entry

PowerSchool Handbook Federal Survey Card Report

Join Queries in Cognos Analytics Reporting

Road Map for Essential Studio 2011 Volume 4

Creating Reports in Access 2007 Table of Contents GUIDE TO DESIGNING REPORTS... 3 DECIDE HOW TO LAY OUT YOUR REPORT... 3 MAKE A SKETCH OF YOUR

Teamcenter Mobility Product decisions, anywhere, anytime. Features. Siemens AG All Rights Reserved.

Working with Data in Microsoft Excel 2010

CA ERwin Data Modeler

6.1 Understand Relational Database Management Systems

GuruFocus User Manual: The FilingWiz

DataGridView FAQ.doc. DataGridView FAQ.doc

VERSION JANUARY 19, 2015 TEST STUDIO QUICK-START GUIDE STANDALONE & VISUAL STUDIO PLUG-IN TELERIK A PROGRESS COMPANY

Microsoft Access II 1.) Opening a Saved Database Music Click the Options Enable this Content Click OK. *

Creating Interactive PDF Forms

COMM 391. Objectives. Introduction to Microsoft Access. What is in an Access database file? Introduction to Microsoft Access 2010

Content Author's Reference and Cookbook

MIS Cases: Decision Making With Application Software, Second Edition. Database Glossary

Database to XML Wizard

Intermediate Microsoft Access 2010

Help Contents. Custom Query Builder Functionality Synopsis

Transcription:

Programming with ADO.NET The Data Cycle The overall task of working with data in an application can be broken down into several top-level processes. For example, before you display data to a user on a form, you must first connect to a data source (possibly a database or a service that provides data), and then fetch the data you want to display. After you bring this data into your application, you may need somewhere to temporarily store it, such as a DataSet. A typical data application will utilize most of the processes illustrated in the following diagram: Connecting to Data To bring data into your application (and send changes back to the data source), some kind of two-way communication needs to be established. This two-way communication is typically handled by the connection of a TableAdapter in applications that use datasets. Connecting your application to data in Visual Studio is simplified by using the Data Source Configuration Wizard. After you complete the wizard, data is available in the Data Sources Window for dragging onto your forms. Preparing Your Application to Receive Data If your application uses a disconnected data model, you need to temporarily store the data in your application while you work with it. Visual Studio provides tools that help you create the objects that your application to temporarily store data: datasets, in our case. Fetching Data into Your Application You need to be able to fetch data into your application. You bring data into your application by executing queries or stored procedures against a database. Applications that store data in datasets execute queries and stored procedures by using TableAdapters. You load data into your application by executing TableAdapter queries, or by calling the Fill method of a data adapter. You execute SQL statements and stored procedures by calling TableAdapter queries, or by executing methods on Command objects. You can call a query on the TableAdapter to load data into data tables in a dataset. Pass the DataTable you want to fill to the TableAdapter query. If your query takes parameters, pass those to the method as well. If the dataset contains multiple tables, you should have separate TableAdapters for each table and must therefore fill each table separately. Displaying Data on Forms in a Windows Application After bringing data into your application, you will typically display it on a form for users to view or modify. Visual Studio provides the Data Sources Window, where you can drag items onto a form to automatically create data-bound controls that display data. MIT 31043, By: S. Sabraz Nawaz Page 1

Editing Data in Your Application Once your users have been presented with data, they will likely modify it by adding new records and editing and deleting records prior to sending the data back to the database. These modifications are made by manipulating the individual DataRow objects that make up the tables in a dataset. Validating Data When making changes to data, you will typically want to verify the changes before allowing the values to be accepted back into the dataset or written to the database. Validation is the name of the process for verifying that these new values are acceptable for the requirements of your application. You can add logic to check values in your application as they change. Saving Data After making changes in your application (and validating those changes), you typically want to send the changes back to the database. Applications that store data in datasets typically use a TableAdapterManager to save data. Data Access Components There are three main data access components in Visual Basic 2008 that you need for retrieving and viewing data from the database: BindingSource, TableAdapter, and DataSet. The BindingSource and DataSet components are located in the Toolbox under the Data tab, as shown in figure. The TableAdapter can be automatically generated depending on the path you take when adding data access components. TableAdapter: The TableAdapter contains the query that is used to select data from your database as well as connection information for connecting to your database. The TableAdapter component does not reside in the ToolBox but it can be automatically generated for you depending on how you add your data access components to your project. It also contains methods that will fill the DataSet in your project with data from the database. You can also choose to have the TableAdapter generate INSERT, UPDATE, and DELETE statements based on the query that is used to select data. DataSet: The DataSet component is a cache of data that is stored in memory. Its data exists in memory. You can use it to store data in tables. In addition to storing data in tables, it stores a rich amount of metadata, or data about the data. This includes things like table and column names, data types, and the information needed to manage and undo changes to the data. Since the DataSet component stores all of the data in memory, you can scroll through the data both forward and backward, and can also make updates to the data in memory. BindingSource: The BindingSource component acts like a bridge between your data source (DataSet) and your data-bound controls (that is, controls that are bound to data components). Any interaction with the data from your controls goes through the BindingSource component, which in turn communicates with your data source. The BindingSource component is the component that you will bind to the DataSource property of your controls. For example, your DataGridView control will be initially filled with data. When you request that a column be sorted, the DataGridView control will communicate that intention to the BindingSource, which in turn communicates that intention to the data source. BindingNavigator: The BindingNavigator component provides a standard User Interface (UI) component that allows you to navigate through the records that are in your data source. The BindingNavigator component is bound to your BindingSource. When you click the Next button in the BindingNavigator component, it in turn sends a request to the BindingSource component for the next record, and the BindingSource component in turn sends the request to the data source. DataGridView: The DataGridView component is a container that allows you to bind data from your data source and have it displayed in a spreadsheet-like format, displaying the columns of data horizontally and the rows of data vertically. The DataGridView component also provides many properties that allow you to customize the appearance of the component itself, as well as properties that allow you to customize the column headers and the display of data. Data Binding: Data binding means taking data referenced by your BindingSource and binding it to a control. In other words, the control will receive its data from your data access components, and the data will be automatically displayed in the control for the user to see and manipulate. MIT 31043, By: S. Sabraz Nawaz Page 2

(Information flows in both direction) In Visual Studio 2013, most controls support some level of data binding. Some are specifically designed for it, such as the DataGridView and TextBox, etc. Connecting to Database: (Throughout this lesson, we are going to use a sample Access 2007/2010 database called Northwind.accdb.) To establish a connection with a database follow this steps. 1. Click Project on the Visual Studio menu bar and then click Add New Data Source.... You should see the Data Source Configuration Wizard. Make sure Database is selected and then click Next >. 2. The Choose a Data Source Type screen allows you to choose the data source for your data. Click the Database icon and click the Next button. 3. In the Choose a Database Model screen, click the Dataset and click Next button. MIT 31043, By: S. Sabraz Nawaz Page 3

1. In the Choose a Database Connection screen, click the New Connection button. 2. In the Add Connection dialog box, click the Browse button and navigate to the folder where your database is and select it. 3. And click OK button in the Add Connection dialog box. 4. Click Next in the Choose a Database Connection dialog box. 5. You will be prompted with a dialog box that informs you that the data file is not part of your project and asks if you want to add it. Click the Yes button in this dialog box. 6. Click the Next button on the Save the Connection String to the Application Configuration File screen. MIT 31043, By: S. Sabraz Nawaz Page 4

7. The Choose Your Database Objects screen allows you to select the data that your application needs. Here you have the option to select data directly. Expand the Tables node in the Database objects list and then select the check boxes for the tables that you want to work with. 8. Click the Finish button when you are done. 9. Now you can see; The Data Sources pane is populated with the tables you selected. The Solution Explorer window is added with Northwind.accdb. 10. Now you have established a connection to the Northwind.accdb Access database. Creating the DataGrid form: 1. In the Data Sources window, select the Customers table, click the drop-down arrow and choose DataGridView from the menu. 2. Drag the main Customers node from the Data Sources window onto the form. Now a datagrid with Customers details and a bindingnavigator are added. MIT 31043, By: S. Sabraz Nawaz Page 5

And also some controls are added in the Component Tray as well. 3. Click the DataGridView control and, in the Properties window, set the Dock property to Fill so that your grid control will occupy the entire form. Creating Detailed form: 01. Add a new form 02. From the Data Sources window, click on the Customers table name, select the blue drop-down arrow by the Customers table and select Details as shown in the figure below. 03. Point at the Customers table name in the Data Sources window drag/drop the table to the form, the form will display labels and TextBox controls for each column in the Customers table as shown in this figure. MIT 31043, By: S. Sabraz Nawaz Page 6

Note the following: Note the new components that were automatically added to the system component tray: o NorthwindDataSet o CustomersBindingSource o CustomersTableAdapter o TableAdapterManager o CustomersBindingNavigator corresponds to the CustomersBindingNavigator control that is automatically added across the top of the form. BindingNavigator: A Move to First Record F Move to Last Record B Move to Previous Record G Add New Record C Current Record (Position) H Delete Current Record D Total Records I Save All Changes E Move to Next Record Using a ComboBox Control to Find Record: You can use a list type of control, such as a ComboBox to make it easier to find student records if the list of customers in the dataset is large, such as when there are several hundred or thousand records. Use a ComboBox to display the Customer s ID value, for example, and then when a value is selected from the ComboBox, display the corresponding values in the other bound controls on the form. MIT 31043, By: S. Sabraz Nawaz Page 7

1. Add a label and accompanying ComboBox control. Label Text property Find: ComboBox Name property cbocustomerid. DropDownStyle DropDownList. 2. Check the Use data bound items check box as shown in the figure below this causes the Data Binding Mode properties to display as shown in the figure: o DataSource CustomersBindingSource. o DisplayMember Company. 3. Run the project and select a Company from the ComboBox. Note: If the column displayed by the DisplayMember property is the primary key column of the table, then you need not set the ValueMember property; otherwise, set ValueMember to the primary key column. Creating a Master-Detail form using two DataGridView Controls:(Customer Order Form) You may want to work with a parent-child relationship. For example, you might want to create a form where selecting a customer record displays the orders for that customer. Displaying the related records on the form is achieved by setting the DataSource property of the child BindingSource to the parent BindingSource (not the child table), and setting the DataMember property of the child BindingSource to the data relation that ties the parent and child tables together. Step I: Creating the Project 1. From the File menu, create a new project. 2. Select Windows Application. 3. Name the project RelatedDataTutorial and click OK. Step II: Creating the Data Source This step creates a dataset based on the Customers and Orders tables in the Northwind sample database. 1. On the Project menu, select Add New Data Source to start the Data Source Configuration Wizard. 2. Select Database on the Choose a Data Source Type page, and then click Next. 3. On the Choose your Data Connection page do one of the following: If a data connection to the Northwind sample database is available in the drop-down list, select it. Or, select New Connection to launch the Add/Modify Connection dialog box, and then click Next. 4. Click Next on the Save connection string to the Application Configuration file page. 5. Expand the Tables node on the Choose your Database Objects page. 6. Select the Customers and Orders tables, and then click Finish. The NorthwindDataSet is added to your project and the Customers table appears in the Data Sources window. Step III: Creating Controls to Display Data from the Customers Table 1. In the Data Sources window, select the Customers table, and then click the drop-down arrow. 2. Choose Details from the menu. 3. Drag the main Customers node from the Data Sources window onto the top of Form1. Data-bound controls with descriptive labels appear on the form, along with a tool strip (BindingNavigator) for navigating records. A NorthwindDataSet, CustomersTableAdapter, BindingSource, and BindingNavigator appear in the component tray. MIT 31043, By: S. Sabraz Nawaz Page 8

Step IV: Creating Controls to Display Data from the Orders Table In the Data Sources window, expand the Customers node and select the last column in the Customers table, which is an expandable Orders node, and drag it onto the bottom of Form1. A DataGridView is added to the form, and a new BindingSource (OrdersBindingSource) and TableAdapter (OrdersTableAdapter) are added to the component tray. Step V: Testing the Application 1. Press F5 to run the application. Select different customers using the CustomersBindingNavigator to verify the correct orders are displayed in the DataGridView. Add a Parameterized Query to a Form in a Windows Application Adding search functionality to a form in a Windows application can be accomplished by running a parameterized query. A parameterized query returns data that meets the conditions of a WHERE clause. You add parameterization to a query by completing the Search Criteria Builder Dialog Box. For example, you can parameterize a query to display only customers in a certain city by adding WHERE City =? to the end of the SQL statement that returns a list of customers. To add a query to an existing data-bound form 1. Open the form in the Windows Forms Designer. 2. Select the tag of CustomersTableAdaper 3. Click Add Query from the tag s menu. 4. Select the desired table to add parameterization in the Select data source table area. 5. Type a name in the New query name box if you are creating a new query. -or- Select a query in the Existing query name box. 6. Type a query that takes parameters in the Query Text box. 7. Click OK. A control to input the parameter and a Load button are added to the form in a ToolStrip control. Creating a Form to Filter Data in a Windows Application You might want to display the orders for a specific customer or the details of a specific order. In this scenario, a user enters information into a form, and then a query is executed with the user's input as a parameter. The query returns only the data that satisfies the criteria entered by the user. This example shows how to create a query that returns customers in a specific city, and modify the user interface so that users can enter a city's name and press a button to execute the query. MIT 31043, By: S. Sabraz Nawaz Page 9

You can add parameterized queries to any TableAdapter (and controls to accept parameter values and execute the query) using the Search Criteria Builder Dialog Box. Open the dialog box by selecting the Add Query command on the Data menu (or on any TableAdapter smart tag). Step I: Creating the Windows Application 1. From the File menu, create a new project. 2. Name the project WindowsSearchForm. 3. Select Windows Application and click OK. For more information, see Creating Windows-Based Applications. The WindowsSearchForm project is created and added to Solution Explorer. Step II: Creating the Data Source 1. On the Data menu, click Show Data Sources. 2. In the Data Sources window, select Add New Data Source to start the Data Source Configuration Wizard. 3. Select Database on the Choose a Data Source Type page, and then click Next. 4. On the Choose your Data Connection page do one of the following: 5. If a data connection to the Northwind sample database is available in the drop-down list, select it. Or, select New Connection to launch the Add/Modify Connection dialog box, and then click Next. 6. Click Next on the Save connection string to the Application Configuration file page. 7. Expand the Tables node on the Choose your Database Objects page. 8. Select the Customers table, and then click Finish. The NorthwindDataSet is added to your project and the Customers table appears in the Data Sources window. Step III: creating data-bound controls on the form 1. Expand the Customers node in the Data Sources window. 2. Drag the Customers node from the Data Sources window to your form. A DataGridView and a tool strip (BindingNavigator) for navigating records appear on the form. A NorthwindDataSet, CustomersTableAdapter, BindingSource, and BindingNavigator appear in the component tray. Step IV: Adding Parameterization (Search Functionality) to the Query 1. Select the DataGridView control, and then choose Add Query on the Data menu. 2. Type FillByCity in the New query name area on the Search Criteria Builder Dialog Box. 3. At the end of the query text in the Query Text, add WHERE City =?. The query should be similar to: SELECT CustomerID, CompanyName, FROM Customers WHERE City =? 4. Click OK to close the Search Criteria Builder dialog box. A FillByCityToolStrip is added to the form. Step V: Testing the Application 1. Press F5 to run the application. 2. Type London into the City text box and then click FillByCity. The data grid is populated with customers that meet the parameterization criteria. In this example, the data grid only displays customers that have a value of London in their City column. MIT 31043, By: S. Sabraz Nawaz Page 10