Você está na página 1de 25

Microsoft Visual C#

2005 (Part 3 of 4):


ASP.NET 2.0 Data
Binding
Fritz Onion
Cofounder
Pluralsight LLC
http://pluralsight.com/fritz/
Introduction to ASP.NET 2.0

A four-part webcast series for developers new to Microsoft® ASP.NET


(two deliveries: Microsoft® Visual C# and Microsoft® Visual Basic .NET)
Lectures with accompanying labs

Date Topic
Mon, Feb. 19, 10 A.M. ASP.NET 2.0 Fundamentals (C#)
Tue, Feb. 20, 10 A.M. User Interface Elements (C#)
Wed, Feb. 21, 10 A.M. DataBinding and AJAX (C#)
Thu, Feb. 22, 10 A.M. Configuration and Deployment (C#)
Mon, Feb. 19, 1 P.M. ASP.NET 2.0 Fundamentals (VB)
Tue, Feb. 20, 1 P.M. User Interface Elements (VB)
Wed, Feb. 21, 1 P.M. DataBinding and AJAX (VB)
Thu, Feb. 22, 1 P.M. Configuration and Deployment (VB)
Agenda

Data Binding
Declarative Binding and SqlDataSource
GridView
Parameters
Updating, Inserting, and Deleting
DetailsView
Object Data Source
Microsoft® ASP.NET AJAX: Using the
UpdatePanel
Data Binding

Data binding
A mechanism for displaying and modifying
dynamic data from a Web page
ASP.NET supports data binding
Can point controls to database table as source for
data
Displayed content drawn from table
Interface for modifying data built into some
controls (update, delete, insert)
Data Binding
Client Browser Web Server

Default.aspx

Quotes
Database

Data-
binding
Binding Controls to Data

Several ASP.NET controls designed to bind


to data
GridView
Display/edit a database table as a grid
DetailsView
Display one table row at a time, insert new items
BulletedList
Display a list of items from a table
Many more …
SqlDataSource Control

SqlDataSource control handles data retrieval,


inserts, updates, and deletes
Acts as bridge between database and data-bound
control
Contains SQL statements to perform database
calls
<asp:SqlDataSource ID="QuotesDataSource" runat="server"
SelectCommand="SELECT ID, Author, Quote FROM Quotes"
ConnectionString="…"/>
Adding a GridView

2. Open Database Explorer

3. Drag table onto page

4. Select desired options

5. Optionally Auto Format…

6. Edit Columns and set


ID column Visible=false
1. Set page to Design mode
Generated Source
<asp:GridView ID="GridView1" runat="server"
AllowSorting="True"
AutoGenerateColumns="False" GridView declaration
DataSourceID="SqlDataSource1"
EmptyDataText=“No records.">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID"
ReadOnly="True" SortExpression="ID"
BoundFields for columns
Visible="False" />
<asp:BoundField DataField="Author" HeaderText="Author"
SortExpression="Author" />
<asp:BoundField DataField="Quote" HeaderText="Quote" SqlDataSource declaration
SortExpression="Quote" />
</Columns> SQL query to retrieve data
</asp:GridView>
Connection string pointing
<asp:SqlDataSource ID="SqlDataSource1" runat="server" to local Quotes.mdf file
SelectCommand=
"SELECT ID, Author, Quote FROM Quotes"
ConnectionString=
"<%$ ConnectionStrings:QuotesConnectionString1 %>"/> web.config

Default.aspx <configuration>
<connectionStrings>
<add name="QuotesConnectionString1"
connectionString="Data Source=… "
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
SQL Parameters

SQL supports parameters to fill values in


dynamically
Microsoft® SQL Server™ syntax is @varname
Before executing statement, parameters must be
associated with values

UPDATE Quotes SET Author=@Author WHERE ID=@ID

parameters
SqlDataSource Parameters

How to associate parameters with Add Update

SqlDataSource and Delete


commands with
parameters
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ConnectionStrings:QuotesConnectionString1 %>"
SelectCommand="SELECT [ID], [Author], [Quote] FROM [Quotes]"
UpdateCommand="UPDATE Quotes SET Author=@Author, Quote=@Quote WHERE ID=@ID"
DeleteCommand="DELETE FROM Quotes WHERE ID=@ID">
<UpdateParameters>
<asp:Parameter Name="Author" Type="String" />
<asp:Parameter Name="Quote" Type="String" />
List parameter
<asp:Parameter Name="ID" Type="Int32" />
names and types
</UpdateParameters>
<DeleteParameters>
<asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>

Note: Parameters should always be named the same as the corresponding


column names to work properly with the GridView and DetailsView controls
GridView Updates and Deletes

Once your SqlDataSource has Update and


Delete commands, the GridView can be
enabled with Update and Delete features

Must set DataKeyNames


to identity column name
to support Update/Delete
GridView Updating
Inserting with a DetailsView

DetailsView provides insert feature


Can also be used to display/update/delete one
row at a time

Configure new data source


Inserting with a DetailsView
Add InsertCommand to data source
Enable Inserting and set DefaultMode=Insert
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ConnectionStrings:QuotesConnectionString1 %>"
SelectCommand="SELECT [ID], [Author], [Quote] FROM [Quotes]"
InsertCommand="INSERT INTO Quotes (Author, Quote) VALUES (@Author, @Quote)">
<InsertParameters>
<asp:Parameter Name="Author" Type="string" />
<asp:Parameter Name="Quote" Type="string" />
</InsertParameters>
</asp:SqlDataSource>
Inserting with a DetailsView
Binding to Objects

ObjectDataSource supports binding to middle-tier objects


Data-bound control ObjectDataSource Middle-tier
IDataSource data objects

<asp:ObjectDataSource ID="peopleDataSource"
runat="server" Repository
SelectMethod="GetPeople"
TypeName="PeopleDS" />

public static class PeopleDS {


static public List<Person> GetPeople() {
List<Person> ret = new List<Person>();
// Add Person instances from some source here
return ret;
}
}
Wiring Up a Data Access Layer

<asp:ObjectDataSource ID="ds1" runat="server"


DataObjectTypeName="PS.MyObject"
DeleteMethod="DeleteMyObject"
InsertMethod="InsertMyObject"
MaximumRowsParameterName="maxRows"
SelectMethod="GetMyObjects"
SortParameterName="sortExpression"
TypeName="PS.DataAccessLayer"
UpdateMethod="UpdateMyObject"
StartRowIndexParameterName="startRowIndex">
<DeleteParameters>
<asp:Parameter Name="objectId" Type="Int32" />
</DeleteParameters>
</asp:ObjectDataSource>
ASP.NET AJAX

ASP.NET AJAX features added after release


Official release in February 2007
Three core components to release
ASP.NET AJAX Extensions (current supported
features)
ASP.NET AJAX Community Technology Preview
(CTP) (preview future features)
ASP.NET AJAX Control Toolkit (community-
driven "collaborative source" controls)
UpdatePanel

Enables partial page rendering


Asynchronous JavaScript And XML (AJAX)-style
pages without custom client script
All postback requests within a panel altered to be
AJAX calls
Fallback to normal postback if client doesn’t
support it
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
--controls go here--
</ContentTemplate>
</asp:UpdatePanel>
UpdateProgress Control

UpdateProgress control displays content during an


UpdatePanel’s asynchronous postback
Common to embed animated GIF, or simple message
By default, shows up for all update panels
Can set AssociatedUpdatePanelID to associate with just
one panel

<asp:UpdateProgress runat="server" ID="UpdateProgress1“


AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
Processing...
</ProgressTemplate>
</asp:UpdateProgress>
Summary

Declarative data sources


Reduce code, move data access code into framework
Data binding
Implicit with declarative data sources
Parameters
Each data source is completely customizable with parameters
Connection strings
New storage location in web.config
ASP.NET AJAX
Easily incorporate asynchronous JavaScript calls
Lab Work

Lab 03 - Data Binding


Use declarative data sources
Use the GridView and DetailsView
Use parameters in a declarative data source
Hierarchical data binding
Questions and Answers

Submit text questions using the “Ask” button.


Don’t forget to fill out the survey.
For upcoming and previously live webcasts:
www.microsoft.com/webcasts
Got webcast content ideas? Contact us at:
http://go.microsoft.com/fwlink/?LinkId=41781
Today's webcast was presented using Microsoft®
Office Live Meeting. Get a free 14-day trial by
visiting: www.microsoft.com/presentlive

Você também pode gostar