Upload
ngoquynh
View
216
Download
0
Embed Size (px)
Citation preview
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
1 Dept: CE AWT (3360706) Piyush Bhut
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, read-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.
The Data Provider has four core objects:
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
2 Dept: CE AWT (3360706) Piyush Bhut
Connection
The Connection object is the first component of ADO.NET. The connection object opens a connection
to your data source.
Connection object helps 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\SQLEXPRESSREPORT; 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
objcmd.CommandText = "insert into Student(StudentID, StudentName) values (1,'abc')"
objcmd.ExecuteNonQuery()
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
3 Dept: CE AWT (3360706) Piyush Bhut
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";
TableMappings Represents a collection of mappings between actual data source table and a DataTable object.
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
4 Dept: CE AWT (3360706) Piyush Bhut
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 DataSet object.
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.
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:
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
5 Dept: CE AWT (3360706) Piyush Bhut
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.
Dim objConn As New SqlConnection
objConn.ConnectionString="Data Source=PRB-PC\SQLEXPRESSREPORT;Initial Catalog=Demo;Integrated
Security=True"
objConn.Open()
Dim objcmd As New SqlCommand
objcmd.Connection = objConn
objcmd.CommandType = CommandType.Text
objcmd.CommandText = "select * from Student"
Dim objDA As New SqlDataAdapter()
Dim objDS As New DataSet("StudentDS")
objDA.SelectCommand = objcmd
objDA.FillSchema(objDS, SchemaType.Source, "Student")
objDA.Fill(objDS, "Student")
objConn.Close()
Dim objDTStudent As DataTable
objDTStudent = objDS.Tables("Student")
Dim objCB As New SqlCommandBuilder(objDA)
Dim row As DataRow
row = objDTStudent.NewRow
row("StudentID") = 6
row("StudentName") = "piyush"
objDTStudent.Rows.Add(row)
objConn.Open()
objDA.Update(objDS, "Student")
For i = 0 To objDS.Tables("Student").Rows.Count - 1
Label3.Text += objDS.Tables("Student").Rows(i).Item("StudentName") + " ".ToString
Next
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
6 Dept: CE AWT (3360706) Piyush Bhut
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=PRB-PC\SQLEXPRESSREPORT;Initial Catalog=Demo;Integrated
Security=True"
Dim str As String = "select * from Student"
Dim objDA As New SqlDataAdapter(str, objConn)
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()
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 CountryList.aspx <asp:HyperLink ID="hlAddCountry" runat="server" NavigateUrl="~/AddEditCountry.aspx">Add Country</asp:HyperLink> <asp:Button ID="btnDisplay" runat="server" Text="Display" /> <asp:GridView ID="dgvCountry" runat="server"> <Columns > <asp:TemplateField HeaderText ="Delete"> <ItemTemplate>
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
7 Dept: CE AWT (3360706) Piyush Bhut
<asp:Button ID ="btnDelete" runat ="server" Text="Delete" CommandName ="DeleteRecord" CommandArgument ='<%# Eval("CountryID") %>' />
</ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText ="Edit"> <ItemTemplate>
<asp:HyperLink id="hlEdit" runat ="server" Text="Edit" NavigateUrl ='<%#"~/AddEditCountry.aspx?CountryID=" + Eval("CountryID").ToString() %>'> </asp:HyperLink>
</ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> CountryList.aspx.vb Protected Sub dgvCountry_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles dgvCountry.RowCommand If e.CommandName = "DeleteRecord" Then Dim objConn As New SqlConnection objConn.ConnectionString = "Data Source=PRB-PC\SQLEXPRESSREPORT; Initial
Catalog=Demo;Integrated Security=True" objConn.Open() Dim objcmd As New SqlCommand objcmd.Connection = objConn objcmd.CommandType = CommandType.Text objcmd.CommandText = "Delete from Country where CountryID=" +
e.CommandArgument.ToString() objcmd.ExecuteNonQuery() dgvCountry.DataBind() objConn.Close() End If End Sub
Protected Sub btnDisplay_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDisplay.Click Dim objConn As New SqlConnection objConn.ConnectionString = "Data Source=PRB-PC\SQLEXPRESSREPORT; Initial Catalog=Demo;Integrated Security=True" objConn.Open() Dim objcmd As New SqlCommand objcmd.Connection = objConn objcmd.CommandType = CommandType.Text objcmd.CommandText = "Select CountryID, CountryName, CountryCode From Country" Dim objDR As SqlDataReader = objcmd.ExecuteReader() dgvCountry.DataSource = objDR dgvCountry.DataBind() End Sub
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
8 Dept: CE AWT (3360706) Piyush Bhut
AddEditCountry.aspx
<table> <tr><h1>Country Entry Form</h1></tr> <tr><asp:Label ID="lblMessage" runat="server" EnableViewState="False"></asp:Label></tr>
<tr><td>*</td> <td>Country Name</td> <td>:</td> <td><asp:TextBox ID="txtCountryName" runat="server"></asp:TextBox></td> <td><asp:RequiredFieldValidator ID="rfvCountryuName" runat="server"
ControlToValidate="txtCountryName" Display="Dynamic" ErrorMessage="Enter Country Name" ForeColor="Red" ValidationGroup="Country"></asp:RequiredFieldValidator></td>
</tr> <tr><td>Country Code</td><td>:</td> <td><asp:TextBox ID="txtCountryCode" runat="server"></asp:TextBox></td></tr> <tr><asp:Button ID="btnSave" runat="server" Text="Save" ValidationGroup="Country"/></tr> </table> AddEditCountry.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
If Request.QueryString("CountryID") = "" Then
lblMessage.Text = "Add Mode"
Else
lblMessage.Text = "Edit Mode, Edit Country Table with CountryID : " +
Request.QueryString("CountryID").ToString()
FillCountryData(Convert.ToInt32(Request.QueryString("CountryID")))
End If
End If
End Sub
Sub FillCountryData(ByVal CountryID As Int32)
Dim objConn As New SqlConnection
objConn.ConnectionString = "Data Source=PRB-PC\SQLEXPRESSREPORT; Initial Catalog=Demo;Integrated
Security=True"
objConn.Open()
Dim objcmd As New SqlCommand
objcmd.Connection = objConn
objcmd.CommandType = CommandType.Text
objcmd.CommandText = "Select CountryID, CountryName, CountryCode From Country Where
CountryID=" + CountryID.ToString()
Dim objDR As SqlDataReader = objcmd.ExecuteReader()
If objDR.HasRows = True Then
While objDR.Read
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
9 Dept: CE AWT (3360706) Piyush Bhut
txtCountryName.Text = objDR("CountryName").ToString()
txtCountryCode.Text = objDR("CountryCode").ToString()
End While
End If
objConn.Close()
End Sub
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim objConn As New SqlConnection
objConn.ConnectionString = "Data Source=PRB-PC\SQLEXPRESSREPORT; Initial Catalog=Demo;Integrated
Security=True"
objConn.Open()
Dim objcmd As New SqlCommand
objcmd.Connection = objConn
objcmd.CommandType = CommandType.Text
If Request.QueryString("CountryID") = "" Then
objcmd.CommandText = "INSERT INTO Country(CountryName, CountryCode) VALUES('" +
txtCountryName.Text.Trim() + "','" + txtCountryCode.Text.Trim() + "')"
objcmd.ExecuteNonQuery()
lblMessage.Text = "Data Inserted Successfully"
txtCountryName.Text = ""
txtCountryCode.Text = ""
txtCountryName.Focus()
objConn.Close()
Else
objcmd.CommandText = "Update Country SET CountryName='" + txtCountryName.Text.Trim() + "',
CountryCode='" + txtCountryCode.Text.Trim() + "' WHERE CountryID=" +
Request.QueryString("CountryID").ToString().Trim()
objcmd.ExecuteNonQuery()
txtCountryName.Text = ""
txtCountryCode.Text = ""
objConn.Close()
Response.Redirect("~/Default.aspx")
End If
End Sub
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.
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
10 Dept: CE AWT (3360706) Piyush Bhut
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.
Insert, Update, Delete and DataBinding operation AddEditProduct.aspx
<table>
<tr>
<td><asp:Label ID="lblProductName" runat="server" Text="Product Name"></asp:Label></td>
<td><asp:TextBox ID="txtProductName" runat="server"></asp:TextBox></td></tr>
<tr>
<td><asp:Label ID="lblProductImage" runat="server" Text="Image"></asp:Label></td>
<td><asp:FileUpload ID="fuProductImage" runat="server" /></td></tr>
<tr>
<td><asp:Label ID="lblProductPrice" runat="server" Text="Price"></asp:Label></td>
<td><asp:TextBox ID="txtPrice" runat="server"></asp:TextBox></td></tr>
<tr>
<td><asp:Label ID="lblProductDiscount" runat="server" Text="Discount"></asp:Label></td>
<td><asp:TextBox ID="txtDiscount" runat="server"></asp:TextBox></td></tr>
<tr>
<td><asp:Label ID="lblProductColor" runat="server" Text="Color"></asp:Label></td>
<td><asp:TextBox ID="txtColor" runat="server"></asp:TextBox></td></tr>
<tr>
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
11 Dept: CE AWT (3360706) Piyush Bhut
<td><asp:Button ID="btnSave" runat="server" Text="Save" /></td>
<td><asp:Label ID="lblMessage" runat="server" Text="Label"></asp:Label></td></tr>
</table>
AddEditProduct.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
If Request.QueryString("ProductID") = "" Then
lblMessage.Text = "Add Mode"
Else
lblMessage.Text = "Edit Mode" + Request.QueryString("ProductID").ToString()
FillProductData(Convert.ToInt32(Request.QueryString("ProductID")))
End If
End If
End Sub
Sub FillProductData(ByVal ProductID As Int32)
Dim objConn As New SqlConnection
objConn.ConnectionString = "Data Source=PRB-PC\SQLEXPRESSREPORT; Initial Catalog=Demo;Integrated
Security=True"
objConn.Open()
Dim objcmd As New SqlCommand
objcmd.Connection = objConn
objcmd.CommandType = CommandType.Text
objcmd.CommandText = "SELECT [ProductName], [Price], [Discount], [Color] FROM [Product] Where
ProductID=" + ProductID.ToString
Dim objDR As SqlDataReader = objcmd.ExecuteReader()
If objDR.HasRows = True Then
While objDR.Read
txtProductName.Text = objDR("ProductName").ToString()
txtPrice.Text = objDR("Price").ToString()
txtDiscount.Text = objDR("Discount").ToString()
txtColor.Text = objDR("Color").ToString()
End While
End If
objConn.Close()
End Sub
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim objConn As New SqlConnection
objConn.ConnectionString = "Data Source=PRB-PC\SQLEXPRESSREPORT; Initial Catalog=Demo;Integrated
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
12 Dept: CE AWT (3360706) Piyush Bhut
Security=True"
objConn.Open()
Dim objcmd As New SqlCommand
objcmd.Connection = objConn
objcmd.CommandType = CommandType.Text
If fuProductImage.HasFile Then
fuProductImage.SaveAs("D:\VS\Diploma 6th 2015\ADOTest\images\" & _fuProductImage.FileName)
End If
If Request.QueryString("ProductID") = "" Then
objcmd.CommandText = "INSERT INTO Product(ProductName, Price,ProductImage,Discount,Color)
VALUES('" + txtProductName.Text.Trim() + "','" + txtPrice.Text.Trim() + "','~/images/" +
fuProductImage.PostedFile.FileName + "','" + txtDiscount.Text.Trim + "','" + txtColor.Text.Trim + "')"
objcmd.ExecuteNonQuery()
txtProductName.Text = ""
txtPrice.Text = ""
txtColor.Text = ""
txtDiscount.Text = ""
txtProductName.Focus()
objConn.Close()
Else
objcmd.CommandText = "Update Product SET ProductName='" + txtProductName.Text.Trim() + "',
Price='" + txtPrice.Text.Trim() + "',ProductImage='~/images/" + fuProductImage.PostedFile.FileName +
"',Discount='" + txtDiscount.Text.ToString + "',Color='" + txtColor.Text.ToString + "' WHERE ProductID="
+ Request.QueryString("ProductID").ToString().Trim()
objcmd.ExecuteNonQuery()
txtProductName.Text = ""
txtPrice.Text = ""
txtColor.Text = ""
txtDiscount.Text = ""
objConn.Close()
Response.Redirect("~/ProductList.aspx")
End If
End Sub
ProductList.aspx
<asp:DataList ID="dlProduct" runat="server" CellPadding="2" CellSpacing="2" RepeatColumns="3"
RepeatDirection="Horizontal" OnItemCommand="dlProduct_ItemCommand">
<HeaderTemplate>
Product Information
</HeaderTemplate>
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
13 Dept: CE AWT (3360706) Piyush Bhut
<ItemTemplate>
<table border="2" style="width: 150px">
<tr><td style="text-align: center">
<asp:Label ID="ProductNameLabel" runat="server" Text='<%# Eval("ProductName") %>' />
</td></tr>
<tr><td style="text-align: center">
<asp:Image ID="ProductImage" runat="server" ImageUrl='<%# Eval("ProductImage") %>'
Height="200" Width="200" />
</td></tr>
<tr><td>Price:<asp:Label ID="PriceLable" runat="server" Text='<%# Eval("Price") %>' /></td></tr>
<tr><td>Discount:<asp:Label ID="DiscountLabel" runat="server" Text='<%# Eval("Discount") %>' />
</td></tr>
<tr><td>Color:<asp:Label ID="ColorLabel" runat="server" Text='<%# Eval("Color") %>' /></td></tr>
<tr><td><asp:HyperLink ID="hlEdit" runat="server" Text="Edit"
NavigateUrl='<%#"~/AddEditProduct.aspx?ProductID=" + Eval("ProductID").ToString() %>'>
</asp:HyperLink></td></tr>
<tr><td><asp:Button ID="btnDelete" runat="server" Text="Delete"
CommandName="DeleteRecord" CommandArgument='<%# Eval("ProductID") %>' /></td></tr>
</table>
</ItemTemplate>
</asp:DataList>
ProductList.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim objConn As New SqlConnection
objConn.ConnectionString = "Data Source=PRB-PC\SQLEXPRESSREPORT; Initial
Catalog=Demo;Integrated Security=True"
objConn.Open()
Dim objcmd As New SqlCommand
objcmd.Connection = objConn
objcmd.CommandType = CommandType.Text
objcmd.CommandText = "SELECT ProductName, Price, ProductImage, Discount, Color FROM Product"
Dim objDR As SqlDataReader = objcmd.ExecuteReader()
dlProduct.DataSource = objDR
dlProduct.DataBind()
End If
End Sub
Protected Sub dlProduct_ItemCommand(ByVal source As Object, ByVal e As
System.Web.UI.WebControls.DataListCommandEventArgs) Handles dlProduct.ItemCommand
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
14 Dept: CE AWT (3360706) Piyush Bhut
If e.CommandName = "DeleteRecord" Then
Dim objConn As New SqlConnection
objConn.ConnectionString = "Data Source=PRB-PC\SQLEXPRESSREPORT; Initial
Catalog=Demo;Integrated Security=True"
objConn.Open()
Dim objcmd As New SqlCommand
objcmd.Connection = objConn
objcmd.CommandType = CommandType.Text
objcmd.CommandText = "Delete from Product where ProductID=" + e.CommandArgument.ToString
objcmd.ExecuteNonQuery()
dlProduct.DataBind()
objConn.Close()
Response.Redirect("~/ProductList.aspx")
End If
End Sub
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.
Comment.aspx
<table >
<tr><td><asp:Label ID="lblName" runat="server" Text="Name"></asp:Label></td>
<td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td></tr>
<tr><td><asp:Label ID="lblSubject" runat="server" Text="Subject"></asp:Label></td>
<td><asp:TextBox ID="txtSubject" runat="server"></asp:TextBox></td></tr>
<tr><td><asp:Label ID="lblComment" runat="server" Text="Comment"></asp:Label></td>
<td><asp:TextBox ID="txtComment" runat="server"
TextMode="MultiLine"></asp:TextBox></td></tr>
<tr><td> </td>
<td><asp:Button ID="btnSubmit" runat="server" Text="Submit" /></td>
</tr></table>
<asp:Repeater ID="rpComment" runat="server">
<ItemTemplate>
<table border ="2" style="background-color:#EBEFF0; width:500px">
<tr><td>Subject:<asp:Label ID="lblSubject" runat="server" Text='<%#Eval("Subject") %>'
Font-Bold="true"/></td></tr>
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
15 Dept: CE AWT (3360706) Piyush Bhut
<tr><td ><asp:Label ID="lblComment" runat="server"
Text='<%#Eval("Comment")%>'/></td></tr>
<tr><td>Post By:<asp:Label ID="lblUser" runat="server" Font-Bold="true"
Text='<%#Eval("Name") %>'/></td></tr>
<tr><td>Created Date:<asp:Label ID="lblDate" runat="server" Font-Bold="true"
Text='<%#Eval("PostedDate") %>'/></td></tr>
</table>
</ItemTemplate>
<SeparatorTemplate > <br /> </SeparatorTemplate>
</asp:Repeater>
Comment.aspx.vb
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Dim objConn As New SqlConnection objConn.ConnectionString = "Data Source=PRB-PC\SQLEXPRESSREPORT; Initial Catalog=Demo;Integrated Security=True" objConn.Open() Dim objcmd As New SqlCommand objcmd.Connection = objConn objcmd.CommandType = CommandType.Text objcmd.CommandText = "INSERT INTO CommentInfo(Name, Subject, Comment, PostedDate) VALUES('" +
txtName.Text.Trim() + "','" + txtSubject.Text.Trim() + "','" + txtComment.Text.Trim + "','" + DateTime.Now + "')"
objcmd.ExecuteNonQuery() objConn.Close() txtName.Text = "" txtSubject.Text = "" txtComment.Text = "" txtName.Focus() BindRepeaterData() End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load BindRepeaterData() End Sub
Sub BindRepeaterData() Dim objConn As New SqlConnection objConn.ConnectionString = "Data Source=PRB-PC\SQLEXPRESSREPORT; Initial Catalog=Demo;Integrated Security=True" objConn.Open() Dim objcmd As New SqlCommand objcmd.Connection = objConn objcmd.CommandType = CommandType.Text objcmd.CommandText = "SELECT Name, Subject, Comment, PostedDate from CommentInfo" Dim objDR As SqlDataReader = objcmd.ExecuteReader()
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
16 Dept: CE AWT (3360706) Piyush Bhut
rpComment.DataSource = objDR rpComment.DataBind() End Sub
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>
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
17 Dept: CE AWT (3360706) Piyush Bhut
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.
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
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate >
<asp:Label ID="Label1" runat="server" Text="Update Panel 1"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button2" runat="server" Text="Update Both Panel" />
<asp:Button ID="Button3" runat="server" Text="Update This Panel" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label3" runat="server" Text="Update Panel 2"></asp:Label>
<asp:Label ID="Label4" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
<Triggers><asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" /></Triggers>
</asp:UpdatePanel>
UpdatePanelDemo.aspx.vb
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Label2.Text = DateTime.Now.ToString
Label4.Text = DateTime.Now.ToString
End Sub
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
18 Dept: CE AWT (3360706) Piyush Bhut
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
Label2.Text = DateTime.Now.ToString
Label4.Text = DateTime.Now.ToString
End Sub
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
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<table>
<tr><td>Country Name</td>
<td><asp:TextBox ID="txtCountryName" runat="server"></asp:TextBox></td></tr>
<tr><td>Country Code</td>
<td><asp:TextBox ID="txtCountryCode" runat="server"></asp:TextBox></td></tr>
<tr><td><asp:Label ID="lblMessage" runat="server" Text="Label"></asp:Label></td>
<td><asp:Button ID="Button1" runat="server" Text="Add Country" /></td></tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate >
<img src ="ajax-loader.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
UpdateProgressDemo.aspx.vb
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
System.Threading.Thread.Sleep(5000)
Dim objConn As New SqlConnection
objConn.ConnectionString = "Data Source=PRB-PC\SQLEXPRESSREPORT; Initial Catalog=Demo;Integrated
Darshan Institute of Engineering & Technology for Diploma Studies Unit-5
19 Dept: CE AWT (3360706) Piyush Bhut
Security=True"
objConn.Open()
Dim objcmd As New SqlCommand
objcmd.Connection = objConn
objcmd.CommandType = CommandType.Text
objcmd.CommandText = "INSERT INTO Country(CountryName, CountryCode) VALUES('" +
txtCountryName.Text.Trim() + "','" + txtCountryCode.Text.Trim() + "')"
objcmd.ExecuteNonQuery()
lblMessage.Text = "Data Inserted Successfully"
txtCountryName.Text = ""
txtCountryCode.Text = ""
txtCountryName.Focus()
objConn.Close()
End Sub