You are on page 1of 18

ADO.NET ActiveX Data Object (ADO) .NET Application to communicate with a database for inserting,updating and retrieving data.

Features 1. Disconnected Architecture Applications connect to the database only while retrieving and updating data. After data is retrieved, the connection with the database is closed. 2. Data cached in Datasets A dataset is a cached set of database records. We can work with the records stored in a dataset as we work with real data; the only difference being that the dataset is independent of data source and we remain disconnected from the data source. As a result, resources are saved and the database can meet the increasing demands of users more efficiently. 3. Data Transfer in XML Format XML is an industry standard Format for exchaning information between different applications. Since a Dataset is stored in the XML format, we can transmit it between different types of application that support XML and any component that can read the dataset structure can process the data. 4. Interaction with the database is done through data commands All operations on the database are performed by using data commands. A data command can be a SQL statement or a Stored procedure.

ADO.NET Object Model PROVIDERS CONNECTION DATAREADER COMMAND DATABASE

VB.NET Application (Windows/Web Forms)

DATASET

DATA ADAPTER

Provider -> The Data residing in a database is retrieved through data provider. Dataset -> The Data is cached in a dataset and the application accesses the data from the dataset. DataReader -> In this method, a DataReader object, which is component of the data provider, uses the connection object to connect to the database, uses the command object to retrieves data, and provides data to the application in a read-only and forward only mode.

Data Providers Two types of Data Providers: OLE DB Data Provider Works with all type of OLEDB Providers. namespace -> System.Data.OleDb SQL Server Data Provider

Working with SQL Server namespace -> System.Data.SqlClient Connection ConnectionString () -> Specify the name of the server, username, password etc. Open() -> Establish the connection Close() -> Close the Connection State -> 0 value indicates the connection is closed 1 value indicates the connection is opened. Eg: Connecting with SQL - Server Imports System.Data.SqlClient Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim con As SqlConnection con = New SqlConnection("server=server;Database=Master;user id=sa;password=killer") con.Open() MsgBox("Connection Opened") con.Close() End Sub Connecting with MS - Access Imports System.Data.OleDb Dim con As OleDbConnection con = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:/demo/vb.net/sampleDB.mdb") con.Open()

MsgBox("Database Connected") con.Close() Data Adapter Data is transfered to and from a database through a data adapter. SqlDataAdapter -> SQL - Server OleDbDataAdapter -> Other Database Properties and Methods of Data Adapter SelectCommand -> Refers to a SQL Statement or a Stored procedure to retrieve data from the database InsertCommand -> Refers to a data command to insert data into a database UpdateCommand -> Refers to a data command to update a database DeleteCommand -> Refers to a data command to delete from a database Fill() Method -> Fills the dataset with the records from a database Update() Method -> Executes the correspoding InsertCommand,

UpdateCommand or DeleteCommand row to reflect the changes in the database. Eg: Drag a SqlDataAdapter1 Connect with Database and Select the Table using Query Builder Select SqlDataAdapter1 -> Data Menu -> Generate Dataset -> DSCust Drag a Datagrid Control and set the Datasource = DScust1.CustomerTracking

Codings SqlDataAdapter1.Fill(DsCust1) DataCommand

A DataCommand is a SQL Statement or a Stored procedure that is used to retrieve, Insert, Delete or modify data in a Data source. SQLCommand -> SQL - Server OleDbCommand -> Other Database Eg: Dim con As New SqlConnection Dim command As New SqlCommand con = New SqlConnection("server=system8;database=master;user id=sa;password=killer") command = New SqlCommand("Insert into Customertracking values('C006','Vidhya','Nandhini','23 KK Nagar',23345,'vidhya@rediff.com')", con) Dim r As Integer command.Connection.Open() r = command.ExecuteNonQuery() command.Connection.Close() MsgBox("Record Inserted") DataReader Data Reader is used to retrieve data from a data source in a read only and forward only mode. Methods Used Read() -> Read Current row Close() -> Close the DataReader NextResult() -> Move to Next Record Pointer Eg: Dim custid As String custid = InputBox("Enter Customer ID") Dim con As New SqlConnection

Dim command As New SqlCommand con = New SqlConnection("server=system8;database=master;user id=sa;password=killer") command = New SqlCommand("Select * from customertracking", con) Dim dr As SqlDataReader command.Connection.Open() dr = command.ExecuteReader() While (dr.Read()) If (dr(0) = custid) Then txtCustid.Text = custid txtFname.Text = dr(1) txtLname.Text = dr(2) txtAddress.Text = dr(3) txtPhone.Text = dr(4) txtEmail.Text = dr(5) End If End While command.Connection.Close() End Sub DataSet When a connection is established with the database, the data adapter creates a dataset and stores data in it. After the data is retrieved and stored in a dataset, DATARELATION DATATABLE EXTENDED COLLECTION COLLECTION PROPERTIES the connection with the database is closed. Such working architecture is called disconnected architecture. The dataset acts like a virtual database containing tables,rows and columns. DATARELATION Dataset Object Model DATATABLE DATASET

DATAROW COLLECTION

DATAVIEW

PRIMARYKEY

DATACOLUMN COLLECTION

DataRow

DataColumn

The Dataset is present as a Dataset class in the System.Data namespace. The Components of the dataset object model are Component DataTableCollection DataRelationCollection ExtendedProperties DataTable DataRelation DataRowCollection DataView PrimaryKey DataColumnCollection Description It Contains all the tables retrieved from the data source It contains relationships and the links between tables in a dataset It contains additional information, such as the SQL statement for retrieving data and the date time stamp for the retrieved data It represents a table in the DataTableCollection of a dataset It represents a relationship in the DataRelationCollection of a dataset It contains all the rows in a DataTable It represents a fixed customized view of a DataTable It represents the column that uniquely identifies a row in a DataTable It contains all the columns in a DataTable.

Connecting to a Database There are three methods to create a data adapter. * Manually * Through a Wizard * Using the Server Explorer Window Types of Datasets Datasets are of two types. 1. Typed 2. Untyped. Typed Dataset A typed dataset is derived from the Dataset class and has an associated XML schema, which is created at the time of the creation of the dataset. The XML schema contains information about the dataset structure, such as the tables, columns and rows. Data is transferred from a database into a dataset and from the dataset to another component in XML format. XML Schema Definition (CSD) language is used to define the elements and attributes of XML documents. Since a typed dataset structure is stored in an XML format, the dataset is saved as an XSD file. This structure of a typed dataset is decided at the time of its creation. When a typed dataset is created, the data commands are generated automatically by using the column names from the data source. Tables and their columns can be accessed by their names while programming. Dim custid as string custid = DSCust.CustomerTracking(0).CustID Untyped Dataset An untyped dataset does not have any associated XML schema. In an untyped dataset, the tables and columns are represented as collections. Since an XML schema is not created for an untyped dataset, the structure of an untyped dataset is not known during compilation.

Dim custid as String OleDbDACust.Fill(DSCust) custid CType(DSCust.Tables("CustomerTracking").Rows(0).Item("CustID"),String) * Using Data Adapter * Complex Data Binding -> Data Grid Implementing Simple Data Binding Navigating Between Records For every data source that is bound to a Windows Form, there exists a CurrencyManager object. The CurrencyManager object handles the binding to the data source by keeping a pointer to the current item in the record list. The Currencymanager class is derived from the BindingManagerBase class. If all the Windows Form controls are bound to a single Data source, the form will have one CurrencyManager object associated with it. A BindingContext object, Which is a Windows Form object, is usd to keep track of the existing CurrencyManager objects in a form. WINDOWS FORM CONTROL1 CONTROL2 CONTROL3 CURRENCYMANAGER1 DATA SOURCE 1 =

BINDINGCONTEXT OBJECT

CURRENCYMANAGER2

DATA SOURCE 2

CURRENCYMANAGER3

DATA SOURCE 3

Connecting to a Database through Wizard 1. Drag a OleDB or SqlDataAdpter control 2. Select the Servername and Enter user id,password and select the database 3. Query Builder -> Select the Tablename and add required columns 4. Finish the wizard Creating Dataset 1. Select the OleDB or SqlDataAdapter 2. From Data Menu -> Choose Generate Dataset 3. Enter the Dataset name and select the corresponding table and click ok. Data Binding 1. Simple Data Binding 2. Complex Data Binding Complex Data binding Binding with Listbox, Datagrid Control with multiple values or multiple columns For Datagrid Control Properties DataSource -> Dataset name DataMember -> Table Name ListBox Datasource DisplayMember Simple Data Binding Binding with a single column and single value. Used for Textbox. TextBox Properties DataBindings Text -> Column name Form_Load SqlDataAdapter1.Fill(DSCust) -> Dataset name -> Column name

Navigating Between Records 1. Create data adapter 2. Create dataset 3. Binding with controls. Codings General Declaration Dim bm As BindingManagerBase Form1_Load SqlDACust.Fill(DsCustomer1) bm = Me.BindingContext(DsCustomer1, "CustomerTracking") bm.Position = 0 cmdFirst_Click bm.Position = 0 cmdLast_Click bm.Position = bm.Count - 1 cmdPrevious_Click bm.Position -= 1 cmdNext_Click bm.Position += 1 Filtering and Sorting Data Two types of Filtering 1. Parameterized Queries 2. Filter the Dataset Parameterized Queries 1. Create a SqlDataAdapter-> Select Connection -> Query Builder -> Select CustOrder Table 2. Specify the condition "where Inv=@param" 3. Click next and finish the SqlDataAdapter. 4. Generate the Dataset for SqlDataAdapter 5. Place the controls and bind the Dataset with the controls.

Codings Private Sub cmdSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSearch.Click SqlDataAdapter1.SelectCommand.Parameters("@param").Value = TextBox1.Text DsCust1.Clear() SqlDataAdapter1.Fill(DsCust1) End Sub Filter the Dataset Using Select() method select(condition,sort order) Eg: Private Sub btnSelect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelect.Click Dim dt As DataTable dt = DsCust1.Tables("CustOrder") Dim cond As String Dim sort As String cond = "cost >3000" sort = "custid asc" Dim result() As DataRow result = dt.Select(cond, sort) Dim ctr As Integer For ctr = 0 To result.Length - 1 lstProdid.Items.Add(result(ctr)("custid").ToString) Next End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load SqlDataAdapter1.Fill(DsCust1) End Sub Displaying Data From multiple tables. xsd -> Schema -> Containing conditions for columns Eg: Control sqlDataAdapter1 Properties SelectCommand Settings Select Custid,fname,address from CustomerTracking

SqlDataAdapter2 DataSet

SelectCommand DSMasterDetail1

Select Inv,InvDate,Custid,prodid from CustOrder CustomerTracking CustomerOrder

Double click the DSMasterdetail1.xsd from Solution Explorer Window Create Relation from Toolbox. Drag the Relation object and place it in CustOrder Table. Label Label Label DataGrid TextBox TextBox TextBox Codings Dim bm As BindingManagerBase Form_Load() SqlDataAdapter1.Fill(DsMasterDetail1, "CustomerTracking") SqlDataAdapter2.Fill(DsMasterDetail1, "CustOrder") bm = Me.BindingContext(DsMasterDetail1, "CustomerTracking") Next bm.Position += 1 Previous bm.Position -= 1 Data Updates Design Form for the following Table 1. CustomerDetails Create table CustomerDetails(Custid varchar(10) primary key,CustName varchar(50), Address Varchar(100),phoneno numeric(15),Email varchar(50),regdate datetime) 2. Design the Form and Bind the Control CustomerID Firstname Address DGDetail -> DataSource -> DSMasterDetail1 DataMember -> CustomerTracking -> CustomerTrackingCustOrder txtCustid txtFname txtAddress -> DataBindings -> Text -> CustomerTracking -> CustID -> DataBindings -> Text -> CustomerTracking -> Fname -> DataBindings -> Text -> CustomerTracking ->Address

3. Codings General Declaration Dim bm As BindingManagerBase Dim flag As Integer = 0 Dim dt As DataTable Dim dr As DataRow Dim custid As String Form_Load SqlDataAdapter1.Fill(DsCustomer1) bm = Me.BindingContext(DsCustomer1, "CustomerDetails") bm.Position = 0 btnFirst_Click bm.Position = 0 btnPrev_Click bm.Position -= 1 btnNext_Click bm.Position += 1 btnLast_Click bm.Position = bm.Count - 1 btnAdd_Click ClearText() flag = 1 Dim cid, cidval As String Dim ctr, len As Integer dt = DsCustomer1.Tables("CustomerDetails") len = dt.Rows.Count - 1 If (len < 0) Then cid = "C001" Else dr = dt.Rows(len) cidval = dr("Custid")

cidval = Mid(cidval, 2, 3) ctr = CInt(cidval) If (ctr > 0 And ctr < 9) Then ctr = ctr + 1 cid = "C00" & ctr ElseIf (ctr >= 9 And ctr < 99) Then ctr = ctr + 1 cid = "C0" & ctr Else ctr = ctr + 1 cid = "C" & ctr End If End If txtCustid.Text = cid txtCustname.Focus() ClearText Private Sub ClearText() txtCustid.Text = "" txtCustname.Text = "" txtAddr.Text = "" txtPhno.Text = "" txtEmail.Text = "" txtRdate.Text = "" End Sub btnModify_Click custid = txtCustid.Text flag = 2 btnDelete_Click custid = txtCustid.Text flag = 3 btnSave_Click If flag = 1 Then dt = DsCustomer1.Tables("CustomerDetails") dr = dt.NewRow() dr(0) = txtCustid.Text dr(1) = txtCustname.Text dr(2) = txtAddr.Text dr(3) = txtPhno.Text dr(4) = txtEmail.Text dr(5) = txtRdate.Text

dt.Rows.Add(dr) ElseIf flag = 2 Then dt = DsCustomer1.Tables("CustomerDetails") dr = dt.Rows.Find(custid) dr.BeginEdit() dr(1) = txtCustname.Text dr(2) = txtAddr.Text dr(3) = txtPhno.Text dr(4) = txtEmail.Text dr(5) = txtRdate.Text dr.EndEdit() ElseIf flag = 3 Then dt = DsCustomer1.Tables("CustomerDetails") dr = dt.Rows.Find(custid) dr.Delete() End If SqlDataAdapter1.Update(DsCustomer1, "CustomerDetails") SqlDataAdapter1.Fill(DsCustomer1) bm.Position = 0 txtRdate_GotFocus txtRdate.Text = System.DateTime.Today Crystal Report For Creating Reports and Charts Three Methods 1. Manually 2. Using Standard Expert 3. From an existing Report Manually 1. Create a Windows Form 2. From Project Menu -> Add New Item -> CrystalReport 3. Name -> RevenueReport.rpt -> Click Open button 4. Crystal Report Gallery -> Select "As a blank Report" -> Click Ok 5. In the Field Explorer Window -> Database Fields -> Right Click -> Add/Remove Database 6. Select OLEDB (ADO) -> Microsoft OLEDB for SQL server 7. USer id = sa;password=killer;server=system8;database=master 8. Select Table "CustomerTracking" -> Insert Table - Click Finish 9. From Field Explorer Window -> Drag the Required Fields to Details Section

10. In the Form Window -> Place one crystalReportViewer Control -> Properties -> ReportSource -> Browser and Select the -> RevenueReport.rpt 11. Run the Application Using Standard Expert 1. Create a Windows Form 2. Project Menu -> Add New Item -> CrystalReport 3. Name -> RevenueReport1.rpt -> Click the Open Button 4. Crystal Report Gallery -> Select "Using Standard Expert" -> Click Ok 5. Select OLEDB (ADO) -> Microsoft OLEDB For SQL Server 6. server=system8;user id=sa;password=killer;database=master 7. Select Table "CustOrder" -> Insert Table -> Click Next 8. Select Display Fields -> Click next 9 Select Group Field -> Click Next 10. Select Summarized Field -> Click Next 11. Chart -> Select chart type -> Text -> Title (Revenue Report) -> Click Next 12. Click next 13. Click Next 14. Click Finish 15. In the Form Window -> Place one crystalReportViewer Control -> Properties -> ReportSource -> Browser and Select the -> RevenueReport.rpt Filtering Data report 1. Create a Windows Form 2. Create a SQLDataAdapter -> Select CustOrder and Set the condition as "Cost>3000" 3. Generate a DataSet with the Name of DSReport 4. Project Menu -> Add New Item -> CrystalReport 5. Name -> RevenueReport2.rpt -> Click Open 6. Crystal Gallery Report -> Select "As a blank Report" 7. In the Field Explorer Window -> Database Fields -> Add /Remove Database 8. Select "Project Data" -> ADO.NET -> Datastet -> DSReport -> Custorder 9. From Field Explorer -> Drag the Required Field 10. Group Name Fields -> New -> CustOrder.Prodid 11. Running Total Field -> New -> CustOrder.Cost -> Sum 12. Formula Field -> New -> Enter "Percentage" -> Formulat Editor -> CustOrder.Advance / CustOrder.Cost * 100 13. Drag the Formula Field in the Details Section 14. In the Form Code Window add the following Code Global Declaration Dim cr As New RevenueReport2

Form_Load SqlDataAdapter1.Fill(DsReport1, "Custorder") cr.SetDataSource(DsReport1) CrystalReportViewer1.ReportSource = cr Relating Data Report 1. Create a Windows Form 2. Project Menu -> Add New Item -> CrystalReport 3. Name -> RelatingReport.rpt-> Click Open 4. Crystal Report Gallery -> Select "Using Standard Expert" 5. Select OLEDB (ADO) - > Microsoft OLEDB For SQL - Server 6. Server=system8;user id=sa;password=killer;database=master; 7. Select -> CustomerTracking and CustOrder Table 8. Relating window Displayed -> Click Next 9. Select Displaying Fields and Click NExt 10. Select Group Field and Click Next 11. Select Summarized Field and Click Next 13. Create Chart if need 14. Click the Next and Finish the Report 15. In the Form Window -> Place one crystalReportViewer Control -> Properties -> ReportSource -> Browser and Select the -> RelatingReport.rpt