unit-5 database programming using ado.net & ajax · unit-5 database programming using ado.net...

21
Unit-5 Database Programming using ADO.NET & AJAX 1 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura ADO.NET ARCHITECTURE * ADO.Net is a large set of .Net classes that enable us to retrieve and manipulate data, and update data sources, in very many different ways. The ADO.NET architecture has two main parts: Data Provider (Connected Objects or Connection oriented objects) Data Set (Disconnected objects or Connectionless objects) Data Provider The .NET framework Data Provider are components that have been explicitly designed for data manipulation and fast, forward-only, re1ad-only access to data. .NET Framework data provider is used for connecting to a database, executing commands, and retrieving results. The following lists the data providers that are included in the .NET framework. Data Provider Description SQL Server Provides data access for Microsoft SQL server. Uses the System.Data.SqlClient namespace. OLEDB For data sources exposed by using OLEDB. Uses the System.Data.OleDb namespace. ODBC For data sources exposed by using ODBC. Uses the System.Data.Odbc namespace. Oracle For Oracle data sources. Uses the System.Data.OracleClient namespace.

Upload: others

Post on 09-Jul-2020

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

1 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

ADO.NET ARCHITECTURE * • ADO.Net is a large set of .Net classes that enable us to retrieve and manipulate data, and update data

sources, in very many different ways.

• The ADO.NET architecture has two main parts:

Data Provider (Connected Objects or Connection oriented objects)

Data Set (Disconnected objects or Connectionless objects)

Data Provider • The .NET framework Data Provider are components that have been explicitly designed for data

manipulation and fast, forward-only, re1ad-only access to data.

• .NET Framework data provider is used for connecting to a database, executing commands, and

retrieving results.

• The following lists the data providers that are included in the .NET framework.

Data Provider Description

SQL Server • Provides data access for Microsoft SQL server.

• Uses the System.Data.SqlClient namespace.

OLEDB • For data sources exposed by using OLEDB.

• Uses the System.Data.OleDb namespace.

ODBC • For data sources exposed by using ODBC.

• Uses the System.Data.Odbc namespace.

Oracle • For Oracle data sources.

• Uses the System.Data.OracleClient namespace.

Page 2: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

2 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

• The Data Provider has four core objects:

Connection

• The Connection object is the first component of ADO.NET. The connection object opens a connection

to your data source.

• Connection object hel ps in accessing and manipulating a database. Database transactions are also

dependent upon the Connection object.

• Important properties of the SqlConnection object

ConnectionString - A connection string provides the information that a provider needs to

communicate with a particular database. The Connection String includes parameters such as Server

name and Database name, as well as security information such as user name and password.

• Important methods of the SqlConnection object

Open – opens the connection

Close – close the connection

Imports System.Data.SqlClient Dim objConn As New SqlConnection objConn.ConnectionString = "Data Source=PRB-PC\SQLE XPRESSREPORT; Initial Catalog=Demo;Integrated Security=True" objConn.Open() Label1.Text = "Connection open" objConn.Close() Label2.Text = "Connection closed"

Command

• The Command object is used to perform action on the data source. Command object can execute

stored procedures and SQL commands.

• You can execute SQL queries to return data in a DataSet or a DataReader object. Command object

performs the standard Select, Insert, Delete and Update SQL operations.

• Command object supports a CommandType that specifies how a command string is interpreted.

Text – An SQL command defining the statements to be executed at the data source.

StoredProcedure – The name of the stored procedure. You can use the parameters property of a

command to access input and output parameters.

TableDirect – The name of a table.

• Command objects methods for executing commands based on return value.

ExecuteReader – Returns a DataReader object.

ExecuteScalar – Returns a single scalar value.

ExecuteNonQuery – Executes a command that does not return any rows.

ExecuteXMLReader – Returns an XMLReader.

Dim objcmd As New SqlCommand objcmd.Connection = objConn objcmd.CommandType = CommandType.Text

Page 3: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

3 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

objcmd.CommandText = "insert into Student(StudentID , StudentName) values (1,'abc')" objcmd.ExecuteNonQuery()

Data Reader

• The DataReader is built as a way to retrieve and examine the rows returned in response to your query

as quickly as possible.

• The data returned by a DataReader is always read only. This class was built to be a lightweight forward

only, read only, way to run through data quickly.

• DataReader object works in connected model.

• Important methods of the SqlDataReader object

Read – Moves to the next row.

NextResult – Moves to the next result.

objcmd.CommandText = "select * from Student" Dim objDR As SqlDataReader objDR = objcmd.ExecuteReader() While objDR.Read Label3.Text += objDR("StudentName") + " ".ToString End While

Data Adapter

• The Data Adapter provides the bridge between the Data Set object and the data source.

• The Data Adapter uses command object to execute SQL commands at the data source to both load the

Data Set with data and reconcile changes that were made to the data in the dataset back to the data

source.

• Using an adapter you can read, add, update and delete records in a data source. An adapter has

following most useful properties.

PROPERTY DESCRIPTION

DeleteCommand Represents a DELETE statement or stored procedure for deleting records

from the data source.

objcmd.DeleteCommand.CommandText = "DELETE FROM Student WHERE

StudentID = 1 ";

InsertCommand

Represents an INSERT statement or stored procedure for inserting a new

record to The data source.

objcmd.InsertCommand.CommandText = "INSERT INTO

Student(StudentID,StudentName) VALUE (2, 'smith')";

SelectCommand Represents a SELECT statement or stored procedure can be used to select

records from a data source.

objcmd.SelectCommand.CommandText = "SELECT * FROM Student";

UpdateCommand Represents an UPDATE statement or stored procedure for Updating

recording in a data source.

objcmd.UpdateCommand.CommandText = "UPDATE Student SET

StudentName = 'smith1' WHERE StudentID = 2";

Page 4: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

4 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

TableMappings Represents a collection of mappings between actual data source table and a

DataTable object.

• Important methods of the SqlDataAdapter object

FillSchema - This method adds a DataTable to a DataSet.

Fill – This method fills data records from a DataAdapter to a criobject.

Update - This method stores data from a data set to the data source.

Data Set

• The dataset object is central to supporting disconnected, distributed data scenarios with ADO.NET.

• The dataset is a memory-resident representation of data that provides consistent relational

programming model regardless of the data source.

• The dataset represents a complete set of data, including related tables, constraints, and relationship

among the table.

• The dataset has two major objects:

The DataTableCollection

The DataRelationCollection

The DataTableCollection

• The DataTableCollection contains all the DataTable objects in a DataSet.

• A DataTable is defined in the System.Data namespace and represents a single table of memory

resident data.

• A DataTable contains a collection of rows represented by DataRowCollection which contains the data

in the table.

• It contains a collection of columns represented by a DataColumnCollection, and constraints

represented by a ConstraintCollection, which together define the schema of the table.

The DataRelationCollection

• A relationship represented by the DataRelation object, associates rows in one DataTable with rows in

another DataTable.

• A relationship is analogous to a join path that might exist between primary and foreign key columns in

a relational database.

• A DataRelation identifies matching columns in two tables of a DataSet.

• The essential element of a DataRelation are:

The name of the relationship

The name of the tables being related

The related column in each table

• Relationships can be built with more than one column per table by specifying an array of DataColumn

objects as the key columns.

Page 5: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

5 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

• When you add a relationship to the DataRelationCollection, you can optionally add a UniqueKey

Constraint and a ForeignKeyConstraint to enforce integrity constraints when changes are made to

related column values.

• Important properties of DataSet object:

Tables - The Tables propertly allows us to retrieve the tables contained in the DataSet. This

property returns a DataTableCollection object.

• Important properties and methods of DataTable object:

Columns - Returns the Columns collection.

Rows - Returns the Rows collection.

NewRow - Creates a new DataRow.

• SqlCommandBuilder class in ADO.NET

Provides the feature of reflecting the changes made to a DataSet.

The SqlCommandBuilder object automatically generates the values contained within the

SqlDataAdapter's InsertCommand, UpdateCommand and DeleteCommand properties based on the

initial SelectCommand.

DataView

• The DataView provides different views of the data stored in a DataTable.

• That is we can customize the views of data from a DataTable. DataView can be used to sort, filter, and

search the data in a DataTable , additionally we can add new rows and modify the content in a

DataTable.

• We can create DataView in two ways. Either we can use the DataView constructor, or we can create a

reference to the DefaultView property of the DataTable.

• Important properties of DataView object

RowFilter - Property that gets or sets the expression used to filter the rows.

Sort - Property that gets or sets the columns and sort orders to apply.

Dim objConn As New SqlConnection objConn.ConnectionString = "Data

Source=Aakash\SQLEXPRESSREPORT;Initial Catalog=Demo ;Integrated Security=True"

Dim str As String = "select * from Student" Dim objDA As New SqlDataAdapter(str, objCon n) Dim objDS As New DataSet() objDA.Fill(objDS, "Student") objConn.Close() Dim objDV As New DataView(objDS.Tables(0)) objDV.RowFilter = "StudentName='abc'" objDV.Sort = "StudentID Desc" GridView1.DataSource = objDV GridView1.DataBind()

Page 6: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

GridView

• GridView control provides more flexibility in displaying and working with data from your database in

comparison with any other controls. The GridView control enables you to connect to a datasource and

display data is tabular format, however you have bunch of options to customize the look and feel.

When it is rendered on the page, generally it is implemented through <table> HTML tag.

• RowCommand - Fires when a button is clicked on any row of GridView.(Event)

• DataBind - Binds the data source to the GridView control.

Insert, Update, Delete and DataBinding operation

AddEditStudent.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="AddEditStudent.aspx.vb" Inherits="DataGrid_Small_Example.AddEditStudent" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>AddEditStudentDetail</title> </head> <body> <form id="form1" runat="server"> <table> <tr><h1>Student Detail Form</h1></tr> <tr><asp:Label ID="lblMessage" runat="serve r" EnableViewState="False"></asp:Label></tr> <tr><td>*</td> <td>Student Name</td> <td>:</td> <td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td> <td><asp:RequiredFieldValidator ID="r fvName" runat="server" ControlToValidate="txtName" Dis play="Dynamic" ErrorMessage="Enter Name Please" ForeColor="Red" ValidationGroup="Name"></asp:RequiredFieldValidator ></td> </tr> <tr><td></td> <td>Student Lastname</td> <td>:</td> <td><asp:TextBox ID="txtLastname" runat="server"></asp:TextBox></td></tr> </table> <asp:Button ID="btnSave" runat="server" Tex t="Save"/> </form> </body> </html>

Page 7: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

7 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

AddEditStudent.aspx.vb

Imports System.Data Imports System.Configuration Imports System.Data.SqlClient Public Class AddEditStudent Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then If Request.QueryString("ID") = "" Then lblMessage.Text = "Add Mode" Else lblMessage.Text = "Edit Mode" + Request.QueryString("ID").ToString( ) FillData(Convert.ToInt32(Request.Qu eryString("ID"))) End If End If End Sub Sub FillData(ByVal Stu_ID As String) Dim objConn As New SqlConnection objConn.ConnectionString = "Data Source=AAK ASH\SQLEXPRESS;Initial Catalog=Diploma;Integrated Security=True" objConn.Open() Dim objcmd As SqlCommand Dim str As String = "Select ID, Firstname, Lastname from Student_Detail where ID= '" + Stu_ID + "'" objcmd = New SqlCommand(str, objConn) Dim objDR As SqlDataReader = objcmd.Execute Reader() If objDR.HasRows = True Then While objDR.Read txtName.Text = objDR("FirstName").T oString() txtLastname.Text = objDR("Lastname" ).ToString() End While End If objConn.Close() End Sub Protected Sub btnSave_Click(ByVal sender As Obj ect, ByVal e As EventArgs) Handles btnSave.Click Dim objConn As New SqlConnection objConn.ConnectionString = "Data Source=AAK ASH\SQLEXPRESS;Initial Catalog=Diploma;Integrated Security=True " objConn.Open() Dim objcmd As New SqlCommand

Page 8: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

8 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

objcmd.Connection = objConn objcmd.CommandType = CommandType.Text If Request.QueryString("ID") = "" Then objcmd.CommandText = "INSERT INTO Student_Detail(Firstname,Lastname) VALUES('" + txtN ame.Text.Trim() + "','" + txtLastname.Text.Trim() + "')" objcmd.ExecuteNonQuery() lblMessage.Text = "Data Inserted Succes sfully" txtName.Text = "" txtLastname.Text = "" txtName.Focus() objConn.Close() Response.Redirect("Datagrid.aspx") Else objcmd.CommandText = "Update Student_De tail SET Firstname='" + txtName.Text.Trim() + "', Lastname='" + txtLastname .Text.Trim() + "' WHERE ID=" + Request.QueryString("ID").ToString().Trim() objcmd.ExecuteNonQuery() txtName.Text = "" txtLastname.Text = "" objConn.Close() Response.Redirect("Datagrid.aspx") End If End Sub End Class

Datagrid.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Datagrid.aspx.vb" Inherits="DataGrid_Sm all_Example.Datagrid" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Example of Grid View</title> </head> <body> <form id="form1" runat="server"> <h1 style="text-align:center">Example of GridVi ew</h1> <asp:HyperLink ID="hlAddStudent" runat="server" NavigateUrl="~/AddEditStudent.aspx">Add Student Det ails</asp:HyperLink> <asp:Button ID="btnDisplay" runat="server" Text ="Display" /> <asp:GridView ID="dgvStudent" runat="server "> <Columns > <asp:TemplateField HeaderText ="Delete" > <ItemTemplate>

Page 9: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

9 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

<asp:Button ID ="btnDelete" run at ="server" Text="Delete" CommandName ="DeleteRecord" CommandA rgument ='<%# Eval("ID") %>' /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText ="Edit"> <ItemTemplate> <asp:HyperLink id="hlEdit" r unat ="server" Text="Edit" NavigateUrl='<%#Eval("ID","~/AddEditStu dent.aspx?ID={0}") %>'></asp:HyperLink> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </form> </body> </html>

Datagrid.aspx.vb

Imports System.Data Imports System.Configuration Imports System.Data.SqlClient Public Class Datagrid Inherits System.Web.UI.Page Protected Sub dgvStudent_RowCommand(ByVal sende r As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles dgvStudent.RowCommand If e.CommandName = "DeleteRecord" Then Dim objConn As New SqlConnection objConn.ConnectionString = "Data Source=AAKASH\SQLEXPRESS;Initial Catalog=Diploma;In tegrated Security=True" objConn.Open() Dim objcmd As New SqlCommand objcmd.Connection = objConn objcmd.CommandType = CommandType.Text objcmd.CommandText = "Delete from Stude nt_Detail where ID=" + e.CommandArgument.ToString() objcmd.ExecuteNonQuery() dgvStudent.DataBind() objConn.Close() End If End Sub Protected Sub btnDisplay_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnDisplay.Click

Page 10: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

10 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

Dim objConn As New SqlConnection objConn.ConnectionString = "Data Source=AAK ASH\SQLEXPRESS;Initial Catalog=Diploma;Integrated Security=True" objConn.Open() Dim objcmd As New SqlCommand objcmd.Connection = objConn objcmd.CommandType = CommandType.Text objcmd.CommandText = "Select ID, Firstname, Lastname From Student_Detail" Dim objDR As SqlDataReader = objcmd.Execute Reader() dgvStudent.DataSource = objDR dgvStudent.DataBind() End Sub End Class

DataList

• The DataList Web server control displays data in a format that you can define using templates and

styles. The DataList control is useful for data in any repeating structure, such as a table.

• Template property and Description:

ItemTemplate: Contains the HTML elements and controls to render once for each row in the data

source.

AlternatingItemTemplate: Contains the HTML elements and controls to render once for every

other row in the data source. Typically, you use this template to create a different look for the

alternating rows, such as a different background color than the color that is specified in

the ItemTemplate property.

SelectedItemTemplate: Contains the elements to render when the user selects an item in

the DataList control. Typically, you use this template to visually distinguish the selected row with a

different background or font color.

EditItemTemplate: Specifies the layout of an item when it is in edit mode. This template typically

contains editing controls, such as TextBox controls.

HeaderTemplate and FooterTemplate: Contains the text and controls to render at the beginning

and end of the list, respectively.

SeparatorTemplate: Contains the elements to render between each item. A typical example might

be a line (using an HR element).

• Important properties of DataList Control:

RepeatColumns: The number of columns to display.

RepeatDirection: The direction to render the cells. Possible values are Horizontal and Vertical.

• Important Event of DataList Control:

ItemCommand - Occurs when any button is clicked in the DataList control.

Page 11: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

11 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

Insert, Update, Delete and DataBinding operation

ListViewExample.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="ListViewExample.aspx.vb" Inherits="List_View_Example.ListViewExample" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <fieldset style="width: 300px"><legend> ListView Example</legend> <asp:Table ID="Table1" runat="server" > <asp:TableRow> <asp:TableCell>Firstname</asp:TableCell><asp:TableC ell><asp:TextBox runat="server" ID="txtFirstname"></asp:TextBox></as p:TableCell> </asp:TableRow> <asp:TableRow> <asp:TableCell>Lastname</asp:TableCell><asp:TableCe ll><asp:TextBox runat="server" ID="txtLastname"></asp:TextBox></asp :TableCell> </asp:TableRow> <asp:TableRow> <asp:TableCell></asp:TableCell> </asp:TableRow> </asp:Table> <asp:Button runat="server" ID="btnSave" Text="Save" /> <asp:Button runat="server" I D="btnUpdate" Text="Update" /> </fieldset> </div> <asp:Label ID="lblID" runat="server" /> <h3>Student Information</h3> <asp:ListView ID="ListStudent" runat="s erver" OnItemCommand="ListStudent_ItemCommand" DataKeyName s="ID" > <itemtemplate> <table > <tr> <td style =" width : 10 0px"> <b>ID. :</b> <%#Eval("ID") %>

Page 12: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

12 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

</td> <td style =" width : 20 0px"> <b>FirstName :</b> <%# Eval("Firstname ")%> </td> <td style =" width : 20 0px"> <b>Lastname :</b> <%#Eval("Lastname") %> </td > <td> <asp:Button ID="btndel" runat="server" Text="Delete" tooltip="Delete a record" onclientcli ck="javascript:return confirm('Are you sure to delete record?')" CommandN ame="StudentDelete" CommandArgument='<%# DataBinder.Eval(Container.Data Item, "ID") %>' /> <asp:Button ID="btnupdt " runat="server" Text="Edit" tooltip="Update a record" CommandName=" StudentEdit" CommandArgument='<%# DataBinder.Eval(Container.Data Item, "ID") %>' /> </td> </tr> </table> </itemtemplate> </asp:ListView> </form> </body> </html>

ListViewExample.aspx.vb

Imports System.Data Imports System.Configuration Imports System.Data.SqlClient Public Class ListViewExample Inherits System.Web.UI.Page Dim Name As String Dim Surname As String Dim str As String = "Data Source=AAKASH\SQLEXPR ESS;Initial Catalog=Diploma;Integrated Security=True" Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not IsPostBack Then Me.BindData() End If End Sub Protected Sub BindData()

Page 13: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

13 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

Dim str As String = "Data Source=AAKASH\SQL EXPRESS;Initial Catalog=Diploma;Integrated Security=True" Dim con As New SqlConnection(str) Dim cmd As New SqlCommand("SP_Student_Detai l_S") cmd.CommandType = CommandType.StoredProcedu re 'cmd.Parameters.AddWithValue("@Action", "SE LECT") Dim sda As New SqlDataAdapter() cmd.Connection = con sda.SelectCommand = cmd Dim dt As New DataTable() sda.Fill(dt) ListStudent.DataSource = dt ListStudent.DataBind() End Sub Protected Sub ListStudent_ItemCommand(ByVal sen der As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventAr gs) Handles ListStudent.ItemCommand Dim values As String = e.CommandName Select Case values Case ("StudentEdit") Dim Stu_ID As Integer = Convert.ToI nt32(e.CommandArgument) UpdateRecord(Stu_ID) Case ("StudentDelete") Dim Stu_ID As Integer = Convert.ToI nt32(e.CommandArgument) DeleteRecord(Stu_ID) End Select End Sub Protected Sub UpdateRecord(ByVal St_ID As Integ er) Dim con As SqlConnection = New SqlConnectio n(str) Dim cmd As SqlCommand = New SqlCommand("SP_ Student_Detail_SID", con) cmd.CommandType = CommandType.StoredProcedu re 'cmd.Parameters.AddWithValue("@Action", "SE LECTID") cmd.Parameters.AddWithValue("@ID", St_ID) con.Open() Dim dr As SqlDataReader = cmd.ExecuteReader () If (dr.HasRows) Then dr.Read() lblID.Text = St_ID txtFirstname.Text = dr("Firstname").ToS tring() txtLastname.Text = dr("Lastname").ToStr ing() End If btnSave.Visible = True btnUpdate.Visible = True Me.BindData() End Sub

Page 14: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

14 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

Protected Sub DeleteRecord(ByVal ID As Integer) Dim con As SqlConnection = New SqlConnectio n(str) Dim cmd As SqlCommand = New SqlCommand("SP_ Student_Detail_D", con) cmd.CommandType = CommandType.StoredProcedu re 'cmd.Parameters.AddWithValue("@Action", "DE LETE") cmd.Parameters.AddWithValue("@ID", ID) con.Open() cmd.ExecuteNonQuery() con.Close() Me.BindData() End Sub Protected Sub btnSave_Click(ByVal sender As Obj ect, ByVal e As EventArgs) Handles btnSave.Click Name = txtFirstname.Text Surname = txtLastname.Text Dim con As New SqlConnection(str) Dim cmd As New SqlCommand("SP_Student_Detai l_I") cmd.CommandType = CommandType.StoredProcedu re ' cmd.Parameters.AddWithValue("@Action", "I NSERT") cmd.Parameters.AddWithValue("@Firstname", N ame) cmd.Parameters.AddWithValue("@Lastname", Su rname) cmd.Connection = con con.Open() cmd.ExecuteNonQuery() con.Close() Me.BindData() txtFirstname.Text = "" txtLastname.Text = "" End Sub Protected Sub btnUpdate_Click(ByVal sender As O bject, ByVal e As EventArgs) Handles btnUpdate.Click Dim Stu_ID As Integer Stu_ID = Convert.ToInt32(lblID.Text) Name = txtFirstname.Text Surname = txtLastname.Text Dim objConn As New SqlConnection objConn.ConnectionString = "Data Source=AAKASH\SQLEXPRESS;Initial Catalog=Diploma;In tegrated Security=True " objConn.Open() Dim objcmd As New SqlCommand objcmd.Connection = objConn objcmd.CommandText = "Update Student_Detail SET Firstname ='" & txtFirstname.Text & "', Lastname='" & txtLastname.T ext & "' WHERE ID= '" & Stu_ID & "'" objcmd.ExecuteNonQuery() objConn.Close()

Page 15: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

15 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

txtFirstname.Text = "" txtLastname.Text = "" btnSave.Visible = False btnUpdate.Visible = False lblID.Text = "" txtFirstname.Text = "" txtLastname.Text = "" Me.BindData() End Sub End Class

Repeater

• The Repeater control is used to display a repeated list of items that are bound to the control. The

Repeater control may be bound to a database table, an XML file, or another list of items.

• Repeater is a Data Bind Control. Data Bind Controls are container controls. Data binding is the process

of creating a link between the data source and the presentation UI to display the data. ASP .Net

provides rich and wide variety of controls, which can be bound to the data.

Repeater_Example.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Repeater_Example.aspx.vb" Inherits="Repeator_Control_Example.Repeater_Example " %> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <h3>Repeater Control Example</h3> <div> <table> <tr> <td>Enter Name:</td> <td><asp:TextBox ID="txtName" runat="server"></ asp:TextBox></td> </tr> <tr> <td>Enter Surname:</td> <td><asp:TextBox ID="txtSurname" runat="server" ></asp:TextBox></td> </tr> <tr> <td><asp:Button ID="btnSubmit" runat="server" T ext="Submit" OnClick="btnSubmit_click" /></td> </tr> </table> </div>

Page 16: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

16 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

<div> <asp:Repeater ID="RepterDetails" runat="server" > <HeaderTemplate> <table style="border:1px solid #0000FF; width:5 00px" cellpadding="0"> <tr style="background-color:#FF6600; color:#000 000; font-size: large; font-weight: bold;"> <td colspan="2"> <b>Details are:</b> </td> </tr> </HeaderTemplate> <ItemTemplate> <tr style="background-color:#EBEFF0"> <td> <table style="background-color:#EBEFF0;border-t op:1px dotted #df5015; width:500px" > <tr> <td> <table style="background-color:#EBEFF0;border-t op:1px dotted #df5015;border-bottom:1px solid #df5015; width:500p x" > <tr> <td >Entered Name is: <asp:Label ID="lblName" r unat="server" Font-Bold="true" Text='<%#Eval("Firstname") %>'/></td> <td >Entered Surname is:<asp:Label ID="lblSurna me" runat="server" Font-Bold="true" Text='<%#Eval("Lastname") %>'/></t d> </tr> </table> </td> </tr> <tr> <td colspan="2">&nbsp;</td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> </div> </form> </body> </html>

Repeater.aspx.vb

Imports System.Data Imports System.Configuration Imports System.Data.SqlClient Public Class Repeater_Example

Page 17: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

17 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

Inherits System.Web.UI.Page Dim str As String = "Data Source=AAKASH\SQLEXPR ESS;Initial Catalog=Diploma;Integrated Security=True" Dim con As New SqlConnection(str) Dim cmd As SqlCommand Dim da As SqlDataAdapter Dim ds As DataSet Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not IsPostBack Then repeatdata() End If End Sub Protected Sub btnSubmit_click(ByVal sender As O bject, ByVal e As EventArgs) Handles btnSubmit.Click con.Open() Dim str As String = "insert into Student_De tail (Firstname,Lastname) values ('" + txtName.Text + "' , '" + txtSurname.Text + "')" cmd = New SqlCommand(str, con) cmd.ExecuteNonQuery() con.Close() txtName.Text = "" txtSurname.Text = "" repeatdata() End Sub Protected Sub repeatdata() con.Open() cmd = New SqlCommand("select * from Student _Detail", con) ds = New DataSet() da = New SqlDataAdapter(cmd) da.Fill(ds) RepterDetails.DataSource = ds RepterDetails.DataBind() End Sub End Class

Page 18: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

18 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

AJAX

• AJAX (Asynchronous JavaScript and XML) is the technique that can be used to have communication

between the client and server without needing a postback. The benefit of avoiding postback is faster

response to the user, the page in the browser is not changed/refreshed/posted so the user can

continue to use it while data is sent to the server.

• AJAX is a technology that facilitates this asynchronous communication between the client and server.

• In traditional web pages the entire page is loaded after a postback. The entire page is replaced, the

browser has to dismiss the old one and then draw the new one.

• Major benefits of AJAX functionality in a website include:

Partial page updates - Only the portion of the page that needs updating is posted back and not the

whole page.

Faster user response - Since only subsets of data moves between the client and server, the results

are shown quickly.

Enhanced user interface - With AJAX, desktop like user interface with progress indicators and

timers can be implemented.

Enhanced features - with AJAX features like autocomplete can be implemented (For Example,

TextBox to display words that begin with the prefix typed into the textbox).

ScriptManager * • To use ASP.NET AJAX, you need to place a new web control on your page. This control is the

ScriptManager, and it’s the brains of ASP.NET AJAX.

• It has the basic syntax:

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

• If you create an 'Ajax Enabled site' or add an 'AJAX Web Form' from the 'Add Item' dialog box, the web

form automatically contains the script manager control. The ScriptManager control takes care of the

client-side script for all the server side controls.

Page 19: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

19 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

UpdatePanel

• Ajax updatepanel will help us to avoid full postback of the page i.e., avoid refresh of the whole page

content with postback and allows only partial postbacks. By using Ajax updatepanel we can refresh

only required part of page instead of refreshing whole page.

• Ajax updatepanel contains property called UpdateMode this property is used to specify whether

UpdatePanel is always refreshed during a partial render or if it refresh only when a particular trigger

hit. By default updatepanel contains UpdateMode="Always" if we want to set it conditionally we need

to change this property UpdateMode="Conditional".

• Ajax updatepanel control contains two child tags those are ContentTemplate and Triggers.

• ContentTemplate is used to hold the content of the page means suppose we designed page with some

controls we will place controls inside of the ContentTemplate.

• Triggers we used in a situation like need to refresh updatepanel only whenever I click some button

control in that situation I will define those controls with this Triggers child tag.

UpdatePanelDemo.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="AJAXControl.aspx.vb" Inherits="AJAX_Update_Panel_Sec_Example.AJAXControl " %> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runa t="server" /> <asp:UpdatePanel runat="server" id="UpdateP anel" updatemode="Conditional"> <Triggers> <asp:AsyncPostBackTrigger controlid="Up dateButton2" eventname="Click" /> </Triggers> <ContentTemplate> <asp:Label runat="server" id="DateT imeLabel1" /> <asp:Button runat="server" id="Upda teButton1" onclick="UpdateButton_Click" text="Update" /> </ContentTemplate> </asp:UpdatePanel> <asp:UpdatePanel runat="server" id="UpdateP anel1" updatemode="Conditional"> <ContentTemplate> <asp:Label runat="server" id="DateT imeLabel2" /> <asp:Button runat="server" id="Upda teButton2" onclick="UpdateButton_Click" text="Update" />

Page 20: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

20 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

</ContentTemplate> </asp:UpdatePanel> </div> </form> </body> </html>

UpdatePanelDemo.aspx.vb

Public Class AJAXControl Inherits System.Web.UI.Page Protected Sub UpdateButton_Click(ByVal sender A s Object, ByVal e As EventArgs) Handles UpdateButton1.Click, UpdateButto n2.Click DateTimeLabel1.Text = DateTime.Now.ToString () DateTimeLabel2.Text = DateTime.Now.ToString () End Sub End Class

UpdateProgress

• UpdateProgress controls to display the progress of partial-page updates. If a page contains

UpdatePanel controls, you can also include UpdateProgress controls to keep users informed about the

status of partial-page updates. You can use one UpdateProgress control to represent the progress of

partial-page updates for the whole page. Alternatively, you can include an UpdateProgress control for

every UpdatePanel control.

• Important properties of UpdateProgress

AssociatedUpdatePanelID – ID of the UpdatePanel control from which it is associated with.

DisplayAfter – value in milliseconds before the UpdateProgress control is displayed.

ProgressTemplate – template that defines the content of the UpdateProgress control.

UpdateProgressDemo.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="UpdateProgre ssBar._Default" %>

<asp:ScriptManager ID="ScriptManager1" runat="serve r"></asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="s erver" UpdateMode="Conditional"> <ContentTemplate> <table> <tr><td>Enter Name Here:</td> <td><asp:TextBox ID="txt Name" runat="server"></asp:TextBox></td></tr> <tr><td>Enter Surname Here:</td > <td><asp:TextBox ID="txt Surname" runat="server"></asp:TextBox></td></tr>

Page 21: Unit-5 Database Programming using ADO.NET & AJAX · Unit-5 Database Programming using ADO.NET & AJAX 6 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura GridView • GridView control

Unit-5 Database Programming using ADO.NET

& AJAX

21 Dept: CE AWT (3360706) Prof. Akash N. Siddhpura

<tr><td><asp:Label ID="lblMessa ge" runat="server" ></asp:Label></td> <td><asp:Button ID="btn AddData" runat="server" Text="Add Data" /></td></tr> </table> </ContentTemplate> </asp:UpdatePanel> <asp:UpdateProgress ID="UpdateProgress1" ru nat="server" AssociatedUpdatePanelID="UpdatePanel1"> <ProgressTemplate > <img src ="loading.gif" /> </ProgressTemplate> </asp:UpdateProgress> UpdateProgressDemo.aspx.vb

Protected Sub btnAddData_Click(sender As Object, e As EventArgs) Handles btnAddData.Click System.Threading.Thread.Sleep(500) Dim objConn As New SqlConnection objConn.ConnectionString = "Data Source=AAK ASH\SQLEXPRESS; Initial Catalog=Diploma;Integrated Security=True" objConn.Open() Dim objcmd As New SqlCommand objcmd.Connection = objConn objcmd.CommandType = CommandType.Text objcmd.CommandText = "INSERT INTO Student_D etail(Firstname, Lastname) VALUES('" + txtName.Text.Trim() + "','" + txtSurname.Text.Trim() + "')" objcmd.ExecuteNonQuery() lblMessage.Text = "Data Inserted Successful ly" txtName.Text = "" txtSurname.Text = "" txtName.Focus() objConn.Close() End Sub

• Difference between Dataset & Data adapter

Dataset Data Adapter

It is a disconnected architecture means it provides

you facility of disconnection architecture

It will acts as bridge between dataset and

database

It is a collection of datatable and relations

between tables

It is a disconnected oriented architectures

It is used to hold the multiple tables with data It is used to read the data from database and

bind that data to dataset