Asp.net slide
Trang 1Session 13
ADO.NET - II
Trang 2 The connection object is used to establish a connection between the application and the database
The command object allows us to retrieve and manipulate data in the database
The DataGrid control can be used for viewing the records
When a customized view of the data from a DataSet is required, a
DataView is used.
A DataReader is used when the records of the query result are
viewed one after the other
Trang 3 Understand Data Binding
Implement the Repeater control
Implement the DataList control
Update a database through a form
Work with XML data
Trang 4Data Binding
Data binding is the process of linking the retrieved data to
the control, which will display the data
Data can be bound to all types of controls with a data
binding expression, which is placed between the <
%# %> tags
Data is bound to a control whenever the DataBind()
method is called for that control
Data binding can be performed on various types of data,
Trang 5<script language="C#" runat="server">
void Page_Load(Object sender, EventArgs e) {
Trang 6Simple Properties
<asp:textbox id = "txtControl" AutoPostback="true" runat=
"server" /><br> <br>
<asp:label id = "lblControl" text = <
%#txtControl.Text%> runat = "server" /><br><br>
</form>
</html>
Trang 7Expressions and Methods
<%@ Import Namespace="System.Data" %>
<html>
<title>DataBinding Expressions</title>
<script language="C#" runat="server">
void Page_Load(Object Sender, EventArgs E) {
Response.Write("<center><b><u>DataBinding Expressions</center></b></u><br>");
if(!IsPostBack) {
DataTable mydt = new DataTable();
DataRow mydr;
mydt.Columns.Add(new DataColumn ("Numbers", typeof(Int32)));
Trang 8Expressions and Methods
for (int i=0;i<=5;i++){
mydr = mydt.NewRow();
mydr[0] = i;
mydt.Rows.Add(mydr);
} dlMyList.DataSource = mydt;
Trang 9Expressions and Methods
int Cube(int num)
Square : <%# Square ((int) ((DataRowView) Container.DataItem) ["Numbers"]) %>
Cube : <%# Cube ((int) ((DataRowView) Container.DataItem) ["Numbers"]) %>
Trang 10Expressions and Methods
</ItemTemplate>
</asp:DataList>
</form>
</html>
Trang 11This method is used to evaluate data binding expressions at runtime,
and format the output as required to be displayed in a browser
Example:
Trang 12T e m p l a t e s
ItemTemplate AlternatingItemTemplate HeaderTemplate
FooterTemplate SeparatorTemplate
The Repeater control is a container control, which can be used to display a list
of data repeating a specified template for each item
A template is a set of HTML elements and controls that can be used to format
the layout of a control
Trang 13<script language="C#" runat="server">
void Page_Load(Object Sender, EventArgs e) {
Response.Write("<center><b><u>Repeater</center>
</b></u><br>");
if (!IsPostBack) {
DataTable mydt = new DataTable();
DataRow mydr;
mydt.Columns.Add(new DataColumn ("Numbers", typeof(Int32)));
Trang 14Repeater2.DataSource = mydt;
Repeater2.DataBind();
Trang 15Repeater Example
} }
Trang 18Repeater Output
</form>
</body>
</html>
Trang 19HeaderTemplate FooterTemplate SeparatorTemplate
The DataList control allows the users to specify the flow of data.
Trang 20<script language="C#" runat="server">
void Page_Load(Object Sender, EventArgs e) {
Response.Write("<center><b><u>Data List with Alternating Columns</center></b></u><br>");
if (!IsPostBack) {
DataTable mydt = new DataTable();
DataRow mydr;
mydt.Columns.Add(new DataColumn ("Numbers", typeof(Int32)));
Trang 21DataList Example
mydt.Columns.Add(new DataColumn("Squares",
typeof(Int32)));
mydt.Columns.Add(new DataColumn("Cubes",typeof(Int32))); for (int i=0;i<30;i++)
Trang 24Data Handling in ASP.NET
DATA
Insert
Select Delete
Update
Trang 25Establish Database Connection
Insert data through command object
mySqlCon = new SqlConnection ("server=SQLDB; uid= sa; pwd
=password; database=pubs");
string myinsertCmd = "insert into publishers ( pub_id,
pub_name, city, state, country ) values (@pubid, @pubname,
@city, @state, @country)";
SqlCommand mySqlCom = new SqlCommand(myinsertCmd,
mySqlCon);
Trang 26Inserting Data Example
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<title>Inserting Data in a Database</title>
<script language="C#" runat="server" Debug="true">
Trang 27Inserting Data Example
public void AddPublisher(Object sender, EventArgs e)
{
string strInsert = "insert into publishers ( pub_id, pub_name, city, state, country ) values (@pubid, @pubname,
@city, @state, @country)";
SqlCommand mySqlCom = new SqlCommand(strInsert,
mySqlCon);
mySqlCom.Parameters.Add(new SqlParameter ("@pubid",
SqlDbType.Char, 4));
mySqlCom.Parameters ["@pubid"] Value = txtPub_Id.Text;
mySqlCom.Parameters.Add(new SqlParameter ("@pubname",
Trang 28Inserting Data Example
mySqlCom.Parameters.Add(new SqlParameter("@state",
SqlDbType.Char, 2));
mySqlCom.Parameters ["@state"] Value = txtState.Text;
mySqlCom.Parameters.Add(new SqlParameter ("@country",
Trang 29Inserting Data Example
BindGrid();
}
public void BindGrid()
{
SqlDataAdapter mySqlda = new SqlDataAdapter ("select
* from publishers where pub_id like '99%'", mySqlCon);
DataSet myds = new DataSet();
mySqlda.Fill (myds, "publishers");
dbgMyGrid.DataSource = myds.Tables ["publishers"]
Trang 30Inserting Data Example
Publisher Id should start with 99 and contain 4
digits<br><br>
Pubisher ID:         
<asp:textbox id="txtPub_Id" runat="server"/>
           
<asp:button id="btnSubmit" Text="Submit"
OnClick="AddPublisher" runat="server"/><br>
Trang 31Inserting Data Output
<span id="Message" MaintainState="false" style="font: arial 11pt;" runat="server"/>
Trang 32Updating Data
One way of presenting an interface for updating data, is
to provide a set of data to the user, and allow the user to choose the row to be updated
The DataGrid control can be used to display all the data
to the user, and the user just has to select and update the required row.
User can choose the row to be updated by using
EditCommandColumn provided by DataGrid control
Trang 33Updating Data Contd…
DataGrid control as follows:
<asp:datagrid id="dbgMyGrid" runat="server"
The events to be executed when the user selects the
command in the EditCommandColumn, are specified here
Trang 34Updating Data Contd…
EditItemIndex property facilitates capturing the
index of the selected row for editing
After the row value is assigned to EditItemIndex,
the row becomes editable
Trang 35Updating Data Contd…
mySqlCmd.Parameters ["@pubid"].Value = dbgMyGrid.DataKeys
Trang 36Updating Data Example
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data" %>
<HTML>
<title>Updating Data in a Database</title>
<script language="C#" runat="server">
SqlConnection mySqlCon;
protected void Page_Load(Object Src, EventArgs e)
{
Response.Write("<center><b><u>Updating Data</center></b></u><br>");
mySqlCon = new SqlConnection ("server=SQLDB; uid=sa; pwd=password;database=pubs");
if(!IsPostBack)
BindGrid();
}
Trang 37Updating Data Example Contd…
public void dbgMyGrid_Edit(Object sender,
Trang 38Updating Data Example Contd…
{
dbgMyGrid.Columns[0].HeaderText="Update";
string strUpdate = "UPDATE Publishers SET pub_id = @pubid, pub_name = @pubname, city = @city, state = @state, country =
@country WHERE pub_id = @pubid";
SqlCommand mySqlCmd = new SqlCommand(strUpdate,
Trang 39Updating Data Example Contd…
mySqlCmd.Parameters ["@pubid"] Value =
Trang 40Updating Data Example Contd…
lblMessage.Text = exc.ToString() + "ERROR:
Could not update record, please ensure the fields are
correctly filled out";
}
Trang 41Updating Data Example Contd…
SqlDataAdapter mySqlda = new SqlDataAdapter ("select
* from publishers", mySqlCon);
DataSet myds = new DataSet();
Trang 42Updating Data Example Contd…
<h4><asp:label id="lblMessage" runat="server"> </asp:label>
Trang 43Updating Data Output
Trang 44Deleting Data
performs the tasks of determining the row selected by
the user, and then deleting the row
<asp:DataGrid id="dbgMyGrid" runat="server" DataKeyField="pub_id" OnDeleteCommand=" dbgMyGrid_Delete">
Trang 45Deleting Data Example
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<title>Deleting Data in a Database</title>
<script language="C#" runat="server" Debug="true">
Trang 46Deleting Data Example Contd…
public void dbgMyGrid_Delete(Object sender,
Message.InnerHtml = "<b>Record Deleted</b><br>";
}
Trang 47Deleting Data Example Contd…
Trang 48Deleting Data Example Contd…
dbgMyGrid.DataBind();
}
</script>
<body>
<form runat="server" ID="Form1">
<span id="Message" EnableViewState="false"
runat="server" /><p>
<asp:DataGrid id="dbgMyGrid" runat="server"
DataKeyField="pub_id" OnDeleteCommand=" dbgMyGrid_Delete">
Trang 49Deleting Data - Output
</body>
</html>
Trang 50Handling XML Data
<rootelement xmlns = "x-schema:scheduledSchema.xsl">
FileStream myfs = new FileStream (Server.MapPath
("xmldatagrid.xml") ,FileMode.Open,FileAccess.Read);
StreamReader myreader = new StreamReader(myfs);
DataSet myds = new DataSet();
Trang 51<script language="C#" runat="server">
void Page_Load(Object Src, EventArgs e) {
DataSet myds = new DataSet();
Trang 52<h3><font face="Arial">XML Data for Table:
<asp:label id="lblTableName" runat= "server"/></font>
</h3>
Trang 54 Data binding is the process of linking data retrieved from a
database to the control, which will display the data
Repeater control is a container control, which can be used to
display a list of data This control has no form of its own.
DataList control can be used for displaying data, and it enables to
specify the flow of data.
Values to be passed to the database for insertion are attached to
the command object with the help of the Parameters collection.
Assigning the index of the row to be updated to the EditItemIndex
property makes that row editable.
The System.IO namespace has to be imported to read XML data.
XML data can be read only into a DataSet, and not into a
DataReader