SlideShare a Scribd company logo
1 of 15
Download to read offline
Chapter 10
Data Binding
::II hapter Outline
10.1 Introduction
10.2 Single-Value Data Binding
10.3 Repeated-Value "List", Data Binding
10.4 Data Source Controls
10.5 Adding Data Source Controls using Visual Studio
10.6 Questions
The basic principle ofdata binding is this: you tell a control where to find your data
A
ou want it displayed, and the control handles the rest ofthe details. a
nd
how
In ASP.NET, the term Data Binding implies binding the controls to data that is 1n·
d
'd' d . re eve(!
from the data source an hence prov1 mg a rea or wnte connectivity between the
controls and the data, that they are bound to. se
fiesedata sources can be one ofdatabases, xml files or even, flat files.
Types of ASP.NET Data Binding
There are two types ofASP.NET data binding exist:
I. Single-value binding
2. Repeated-value binding
Single-value data binding is by far the simpler of the two, whereas repeated-value binding
provides the foundation for the most advanced ASP.NET data controls.
3
IW•e:"ya
JitW~·
You can use single-value data binding to add information anywhere on an ASP.NET
page.
You use the single-item data-bound controls to display the value of a single itern of a
database table. These controls don't provide direct binding with the data source.
_,. 1 e data binding doesn't necessarily have anything to do ·th ADO NET
. te-va u . . w1 . .
5,og . gle-value data bmdmg allows you to take avariable apro rty •
d, sm . , pe , or an expression
10stea •t dynamically mto apage.
!) diosert t .
all value binding also helps you create templates for the rich data controls.
Siogle· .
,••ted~4Jlle'"~
"~isK',, ata Binding _
. iteR~~-., & ,., . • ..
j~d-value data bmdmg allm,s You to d,sp1,y a, omre bble (e,ju,t , si,~,field from
Repeate
atable). . g1 -value data binding, this type of data binding requires a special control that
nlike sm e
lJ .
!) rts 1t.
suPPo . .11 be a list control such as CheckBoxList or ListBox, but it can also be amuch
this w1 G·dv·
jcallY, trol such as the n 1ew.
WP . · ted con .
50
ph1sttca 1 an Display Data in Connected and Disconnected Model.
(llore • d contro c
pata Bin data bind controls in ASP.NET:
· gare
foiloWtn
Data Bound Control
Text
Label
Button
Image
Single-item data
bound controls
DataGrid
Datalist
ListBox
DropDownlistBox
Multi-item data
bound controls
ASP.NET Single Value Data Binding Example
Single Value Data Binding Example
ILBllll
- 0 X
Ell: -• • utoEventWiret.Jp="tn.Je" CodeFile="Default.as ••
<%@ Page Language- C# A PX.cs" lnhe .
- -
<html .m•se'lrtlpJ-·"'·""''"'""'rnr> -0,,...
<head n.Jnat=="server"> . . .
. D
I
Binding Example by Haider Sir </title>
<title> Single Value aa
</head>
<body>
<form id="forrn1" runat==•server">
<div>
<table class="style1">
<td class="style3">
<h1>Single Value Data Binding Exarnpie</h1></td>
<td class=•style3">
<asp:Label ID="Label1" runat=="server" Font-Size="X-Large" Font-ltalic="False"
ForeColor-"#000099" Font-Bold="Tn.Je" Font-Names="AR JULIAN">
User ID:<%# UserlD ¾><br />
UserName: <%# UserName ¾><br />
City: <%# City %>
</asp:Label>
</table>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic·
using System.Web.UI; '
using System.Data;
using System.Web UI WebCo
· · ntrols;
public partial class D f
{
_ e ault :System.Web
public int UserlD·
public string Use~ame;
.UI.Page
~ny;
liC str'
~b
ed ~id page_Load(object sender, EventArgs e)
P'°tsGt
( D:::: 110;
userl _•Haider Zaidi";
rr,1arn8 -
usB •,Arnroha";
cilY"
. oataBind();
111,s.
Single Value Data BindingExample
USll ID: DO
USEINAMF.: IIAmEl 7Am1
Cm: AMI.OIL
- 0 X
0111,1e111 ® ~ =
Problems with Single-Value Data Binding
1. Putting code into a page's user interface: One of ASP.NETs great advantages is that it
allows developers to separate the user interface code (the HTML and control tags in
the .aspx file) from the actual code used for data access and all other tasks (in the code-
behind file).
2. Fragmenting code: When using data binding expressions, it may not be obvious where the
functionality resides for different operations.
Repeated-Value Data Binding Example
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" lnherits="_Default"
%>
:IDOCTYPE html PUBLIC •-t/W3C//DTD XHTML
h1tp:/fwww.w3.org/TR/xhtml1 /DTD/xhtml1-transitional.dtd">
1.0 Transitional/JEN"
<htmlxrnlns="http://www.w3.org/1999/xhtml">
<head id="Head1• runat="server">
ctitle>asp.net multiple Binding example: using this.DataBind()</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1 style="color:Navy"> Repeated-Value Data Binding : Example </h
1
>
<asp:ListBox
1D="ListBox1•
runat="server"
BackColor-"#FFCCFF"
ForeColor-"#OOOOCC" Font-Bold="True•
:>
</asp:ListBox>
<br /:><br />
<asp:DropDownList
1D="DropDownList1•
runat="server"
BackColor-"#66FFFF"
ForeColor-"#000099" Font-Bold="True"
:>
</asp:DropDownList>
<br /><br />
<asp:RadioButtonList
ID="RadioButton1List1•
runat="server"
BackColor-"#CCCCFF"
ForeColor-"#OOOQgg•
BorderWidth="2"
BorderColor-"Green" Font-Bold="True"
>
</asp:RadioButtonList>
<br /><br />
<asp:CheckBoxList
ID="CheckBoxList1•
runat="server"
BackColor-"#FFFF99"
ForeColor="#OOOOSS"
BorderWidth="2"
13orde
reolor-="lndianRed" Font-Bold="True"
7 •CheckBoXList>
,/~SP·
,/div7
,~orf117
Jff-lf
<Jlltfll7
olt aspi:.cs=--------------- - --------
vefa .
. systern; .
usin9 collections.Generic;
systern-
usin9 . .
. systern,unq,
usin9 •
. system.Web,
us1n9 u1·
. system.Web. ,
us1n9 Ct 1 •
tern Web.LIi.Web on ro s,
using sys ·
I
. partial class Default : System.Web.UI.Page
pub IC -
{ protected void Page_Load(object sender, EventArgs e)
{
l
if (!this.lsPostBack)
{
l
Ust<string> DataToolBoxControls = new List<string>();
DataToolBoxControls.Add("Zari");
DataToolBoxControls.Add("Haider");
DataToolBoxControls.Add("Zaidi");
ListBox1 .DataSource = DataTooBoxControls;
DropDownlist1 .DataSource = DataTooBoxControls;
RadioButton1 List1 .DataSource =DataTooBoxControls;
CheckBoxlist1 .DataSource = OataTooBoxControls;
this.DataBind();
l
--
Repeated-Value Data Binding: Example
Toe data source controls include any control that implements the IDataSource interface.
Data Source Controk ·, Description Data Source -
,·
/taSource
Designed to work with SQL Server SQL Server 2000 or later. -
databases. It uses Sq! Server .NET
/ data provider internally. Sql
Server .NET data provider classes
are defined~
Systern.Data.SqlClient narnespace.
,,ccessDataSource Designed to work with Microsoft Microsoft Access
/ Access. It uses OleDb data erovider
,
~ -:-"
OleDb data provider
are defined in the
System.Data. OleDb namespace.
ObjectDataSource Designed to work with objects. Q.bject.l!lsually classes provide a
well-define~ ~t.ructure)
XmlDataSource Designed to work with XML XML documents
documents.
. - ---·- ·-- ·-·
SiteMapDataSource Designed to work with SiteMap SiteMap
~~ct
_§,_
which is a new conceet in - -
, .,,.. ASP.NET 4.00
DataSetDataSource Designed to work with QlllaSet
ol?j~cts.
Di!.L
aSet
l) AccessOa .· -- '·
1
~ Obj
... · .:I.Sqq1IDataSource
~; · ectDabdumu:
. ,t/:':l .
SqlDataSource in Toolbox
When you drop SqlDataSource to apage, you will see Configure Data Source link.
/ Defautaspx.cs)'i>efault.~pr1
1B
:SqlDataSource - SqlDataSou;celfCool1lOII SQIData&>urmT•
I
I
Configure Data Source...
[configure your data source's settingsJ
Configure Data Source
Clicking this link launches Configure Data Source wizard, which allows you to configure adata
sourc ·
. _e connection. See Figure below. This wizard allows you to create a new connect10n or use
existing co · · dr d 1·
nnecllons by selecting from data connection op own 1st
Canftfl!!Oatl~-Sqt
a.-•......
Slltd•<~lll UMlntle dllJso,ltl,
qB [H•l?I.., J
DIii dmli
IPmidor.
l,~.;;-,
..___._;
Configure Data Source wizard
Clicking New button of Configure Data Source wizard launches Connection Properties wizar~
which allows you to create anew connection.
----------==
; specfythe foilwilo toconn·ecttoSQl Se - -
1 a@ • · rverdati:
WJ 1, Select or enter a~~: •
prl)l'idef [TOSHIBA-USER
,._______
l~ I
I !t .
i co~netton
!
l
' r@
. Ail
2. Enter nformaooo tll'09on tothe server.
0Use l'{~do:,vs NT Inte!jrated Seauty
0Use aspeciJc user ID and p~d:
IJ8f[O:
e,2ssword: 1
!
; ------======--
!3~av
em1ti,mvord
3, 0Select or enter agatlbase,n;ime:·
[Northwild
0Attic!! adatabase fieasafie -:
Fl
--------:c-:.-- - ,---~ I
~owse... i I
I
IIestConnecti>n J
Connection Properties Wizard
The next dialog of Configure Data Source wizard allows you to specify the variable name of the
connection string,
- ~
Save c:omedlon stm,i ID the appbtion aMlfiglntion file
P111Vide anamefor storing connectionInformation.
...
. . • ' ' • • '  " _. ,
1
1/-~t~';ii:.-:-,.,
stoling:comedionstmos'11'f'OUwebstte's-confiQu,iionlie(Web:CO!?fio)easesm~ncfand deploymentofyouia ,:,1· : :; •
theconn~onstrtng inWeb:config, entera.n~meinthe boxandthendd!lext.If'/OUchoose not~ dothis, thecoin:~t•,Tosave .
savedlq~age'an~rt,-ofthedatasoon:econtrol. ·· ijgij' ...

' •I
Do~ wanttosawe thismn~ i.tJtna'.to~•
..i~:mn~ftlel .
., ' •· " ', ' '
·"~{.
0,I,es.ae th~connecti>n :;
; .
"-
~-pCon
_ ne_
~_ trn
_g
_
l -------::-~
-:~
•··
~i~-::-;/
--~- ::
cancel lL s§ad II l!exl> I' ii] '
Connection String Page
'
th SELECT statement Here you can select a
The following dialog allows you to specify e I .
database table and its columns and add WHERE and ORDER BY c auses.
r;..
teme
econtrol to getdatafrom the database.
tJ
d
-~likf;bremeve,datafromyour databasei~• ·-
IIO;vwau
[_
yo . '. ~• -
_
_ - - ,.
_ _-__~n11sfrom aJilllle orview
@
SPev'.co • __ _
' __
1
,/ ~om§QLstatementorstored procedure
OSPe
v,a· .
· 0 ""nS ___________
_
plfof y~w p... .
V
QuanliyPeJJnit ODiscontinued
-·,Eljiroduct!D OUnitPrtce DcategoryName DR~tum on~u
n
~u
erows
, I'.]productName OUnits!nStock [ WHERE
Elsupplier!D OUnitsOnOrder I
0category!D OReorderlevel OBJ)ER BY
__ -,-----:-_____________J [ A
dyanced Options...
!;ElECT-Statement
[ cancel 11 <Jlack ]I Next > I.___ Ffl=---i;,r,
-·_
Configure Select Statement Dialog
The next dialog tests the data.
til· ~ -
.f.f¥.t!'94' .
- • • sIDataSource1
.
Configure Data Source · Q
Test(!uely
Execute the selectstarement to previewtheresult
- T completethis wiZard, did< Rnlsh.
. e did rest Query, 0
To preview thedata returned bythis data soorr '
IUntl'rice IUnits!nStocklUnitsOnOrderl1.
-!'
.,i
I5uppierlllIcitegorylllIQuantlyi'erJnt 39 0 liLJ
ProductJDIProductName
1
Ii 1oboxesx20bags 18.0000
I Olai
1
1
24. 12 oz bottles 19.0000 17 K
O 2_
2 Oiang
I 70 ;
1
2
12 . 550 rn bottles 10.0000 13
3 Mi.eed Syrup
I 0 C
1
2 48 -6 oz jars 22.0000 53
OiefAnton's Cljun Seasonil0 2
4 1
2 12 -8 ozjars 25.0000 120 0 2
Grandma's so~nberrv Spread
p
6
1
7
12 •1bpkgs. 30.0000 15 0 1
unde Bob's oroani: Dried Pears
7
/2
12•12 oz jars 40.0000 6 0 :
er.
8 Northwoods eranbell)' Sauce 3 J. _
.
dl~
I. - ~.- .. .. T
$·,1
. ml
[ Jelt Quel'( I
SflfCT Statement
58.f{T • FROM [At>habeti:al1st of products]
-
.
--
-
--
-
[ cancel ][ <!lack ]_ k"1.1:--;- [ [flish I
Test Query Dialog
Now this entire action adds the following code to the HTML file:
<asp:SqlDataSource ID="SqlDataSourcel" Runat="server"
SelectCommand="SELECT * FROM [Alphabetical list of products]"
ConnectionString="<$ connectionStrings:AppConnectionStringl >">
</asp:SqlDataSource>
Ifyou do not have Visual Studio, you can create SqlDataSource control in HTML by editing the
HTML code. As you can see from this code, tag <asp:SqlDataSource> represents the SqlDataSource
control and like other controls, you can set its parameters in HTML file. The above code sets
SelectCommand and ConnectionString parameters of SqlDataSource control.
You can also set the controls parameters from Properties window. As you can see from Figure
Connection string page, you can set various properties of SqlDataSource including ConncctionString
and SelectQuery.
pg
SqlDa~
. _Itel Syste
m
.Web
~fWjJ§J .UJ.Webc~
ntrols.SqlDataSource .
-
I(Expressions) .- .
[ea~ ISqlDatiSoun:el
-- -
JCacheExpirationPol lnmite
- ~ Icy~ -
,....,,,.,,,., ""'"'
eance15~~l
--
:~ IOverwrn:eChanges
. ~ - ill1
Se.rver=TOSHIBMJSER;IntegrateJ!_
,· - IDataSet
,,!DeleteQuery (
:;i - - Query)
"]EnableCaching Fls
.. a e
. !~~~ leVieWState 'I True
:J
Rlter£xpression I
jRlter?arameters I(Colection)
r•"l"•• 'Iq,..,J
Ol~ aluesParameterFormatstring Ioriginal_{0}
ProviderName I
~eiectQuery . (Query)
ISortParameterName !
Sq!CacheDependency
_1 UpdateQuery (Query)
SelectQuery
Select Query
SqlDataSource Properties
If you InsertQuery property, it launches Command and Parameter Editor, where you can add and
remove parameters. See Figure Configure Select Statement dialog. From this dialog, you can also
launch Query Builder, which allows you to create a SQL query.
sa.ECT~ommand:
~CT • FROM [~abeto1st ofproducts]
Refregi .J
f~15l ·
Name I vaie- ifw,;:,;. ·,:;::: t
. ·,
[
Command and Parameter Editor
l. What is data binding? Explain its different types with example.
2. Explain problem with single value data binding with example.
3. Explain different data source ofADO.NET.

More Related Content

Similar to Advanced Web Programming Chapter 10

Qtp connect to an oracle database database - database skill
Qtp connect to an oracle database   database - database skillQtp connect to an oracle database   database - database skill
Qtp connect to an oracle database database - database skill
siva1991
 
2005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.0
2005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.02005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.0
2005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.0
Daniel Fisher
 
My sql with querys
My sql with querysMy sql with querys
My sql with querys
NIRMAL FELIX
 

Similar to Advanced Web Programming Chapter 10 (20)

Qtp connect to an oracle database database - database skill
Qtp connect to an oracle database   database - database skillQtp connect to an oracle database   database - database skill
Qtp connect to an oracle database database - database skill
 
Ado.Net
Ado.NetAdo.Net
Ado.Net
 
Jdbc
JdbcJdbc
Jdbc
 
Asp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptxAsp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptx
 
Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
 
ADO.NET by ASP.NET Development Company in india
ADO.NET by ASP.NET  Development Company in indiaADO.NET by ASP.NET  Development Company in india
ADO.NET by ASP.NET Development Company in india
 
2005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.0
2005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.02005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.0
2005 - .NET Chaostage: 1st class data driven applications with ASP.NET 2.0
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.net
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
My sql with querys
My sql with querysMy sql with querys
My sql with querys
 
Database programming
Database programmingDatabase programming
Database programming
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 
Ado.net
Ado.netAdo.net
Ado.net
 
Unit4
Unit4Unit4
Unit4
 
Data handling in r
Data handling in rData handling in r
Data handling in r
 
Csharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptxCsharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptx
 
Slice for Distributed Persistence (JavaOne 2010)
Slice for Distributed Persistence (JavaOne 2010)Slice for Distributed Persistence (JavaOne 2010)
Slice for Distributed Persistence (JavaOne 2010)
 
ADO.NET Data Services &amp; Entity Framework
ADO.NET Data Services &amp; Entity FrameworkADO.NET Data Services &amp; Entity Framework
ADO.NET Data Services &amp; Entity Framework
 
Advanced SQL - Database Access from Programming Languages
Advanced SQL - Database Access  from Programming LanguagesAdvanced SQL - Database Access  from Programming Languages
Advanced SQL - Database Access from Programming Languages
 
WEB PROGRAMMING USING ASP.NET
WEB PROGRAMMING USING ASP.NETWEB PROGRAMMING USING ASP.NET
WEB PROGRAMMING USING ASP.NET
 

More from RohanMistry15

Artificial Intelligence - A modern approach 3ed
Artificial Intelligence - A modern approach 3edArtificial Intelligence - A modern approach 3ed
Artificial Intelligence - A modern approach 3ed
RohanMistry15
 

More from RohanMistry15 (20)

software-quality-assurance question paper 2023
software-quality-assurance question paper 2023software-quality-assurance question paper 2023
software-quality-assurance question paper 2023
 
security-in-computing question paper 2023
security-in-computing question paper 2023security-in-computing question paper 2023
security-in-computing question paper 2023
 
IT-service-management question paper 2023
IT-service-management question paper 2023IT-service-management question paper 2023
IT-service-management question paper 2023
 
geographical-information-system question paper
geographical-information-system question papergeographical-information-system question paper
geographical-information-system question paper
 
Business-Intelligence question paper 2023
Business-Intelligence question paper 2023Business-Intelligence question paper 2023
Business-Intelligence question paper 2023
 
Aeronautical Engineering Career Information
Aeronautical Engineering Career InformationAeronautical Engineering Career Information
Aeronautical Engineering Career Information
 
Chinese Cyber attack on mumbai power plant
Chinese Cyber attack on mumbai power plantChinese Cyber attack on mumbai power plant
Chinese Cyber attack on mumbai power plant
 
Zeus learning
Zeus learningZeus learning
Zeus learning
 
Artificial Intelligence - A modern approach 3ed
Artificial Intelligence - A modern approach 3edArtificial Intelligence - A modern approach 3ed
Artificial Intelligence - A modern approach 3ed
 
Advanced Web Programming Chapter 8
Advanced Web Programming Chapter 8Advanced Web Programming Chapter 8
Advanced Web Programming Chapter 8
 
Advanced Web Programming Chapter 5
Advanced Web Programming Chapter 5Advanced Web Programming Chapter 5
Advanced Web Programming Chapter 5
 
Advanced Web Programming Chapter 4
Advanced Web Programming Chapter 4Advanced Web Programming Chapter 4
Advanced Web Programming Chapter 4
 
Advanced Web Programming Chapter 13 & 14
Advanced Web Programming Chapter 13 & 14Advanced Web Programming Chapter 13 & 14
Advanced Web Programming Chapter 13 & 14
 
Advanced Web Programming Chapter 12
Advanced Web Programming Chapter 12Advanced Web Programming Chapter 12
Advanced Web Programming Chapter 12
 
Advanced Web Programming Chapter 2
Advanced Web Programming Chapter 2Advanced Web Programming Chapter 2
Advanced Web Programming Chapter 2
 
Advanced Web Programming Chapter 3
Advanced Web Programming Chapter 3Advanced Web Programming Chapter 3
Advanced Web Programming Chapter 3
 
Advanced Web Programming Chapter 11
Advanced Web Programming Chapter 11Advanced Web Programming Chapter 11
Advanced Web Programming Chapter 11
 
Advanced Web Programming Chapter 9
Advanced Web Programming Chapter 9Advanced Web Programming Chapter 9
Advanced Web Programming Chapter 9
 
Advanced Web Programming Chapter 6
Advanced Web Programming Chapter 6Advanced Web Programming Chapter 6
Advanced Web Programming Chapter 6
 
Advanced Web Programming Chapter 1
Advanced Web Programming Chapter 1Advanced Web Programming Chapter 1
Advanced Web Programming Chapter 1
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Advanced Web Programming Chapter 10

  • 1. Chapter 10 Data Binding ::II hapter Outline 10.1 Introduction 10.2 Single-Value Data Binding 10.3 Repeated-Value "List", Data Binding 10.4 Data Source Controls 10.5 Adding Data Source Controls using Visual Studio 10.6 Questions The basic principle ofdata binding is this: you tell a control where to find your data A ou want it displayed, and the control handles the rest ofthe details. a nd how In ASP.NET, the term Data Binding implies binding the controls to data that is 1n· d 'd' d . re eve(! from the data source an hence prov1 mg a rea or wnte connectivity between the controls and the data, that they are bound to. se fiesedata sources can be one ofdatabases, xml files or even, flat files. Types of ASP.NET Data Binding There are two types ofASP.NET data binding exist: I. Single-value binding 2. Repeated-value binding Single-value data binding is by far the simpler of the two, whereas repeated-value binding provides the foundation for the most advanced ASP.NET data controls. 3 IW•e:"ya JitW~· You can use single-value data binding to add information anywhere on an ASP.NET page. You use the single-item data-bound controls to display the value of a single itern of a database table. These controls don't provide direct binding with the data source.
  • 2. _,. 1 e data binding doesn't necessarily have anything to do ·th ADO NET . te-va u . . w1 . . 5,og . gle-value data bmdmg allows you to take avariable apro rty • d, sm . , pe , or an expression 10stea •t dynamically mto apage. !) diosert t . all value binding also helps you create templates for the rich data controls. Siogle· . ,••ted~4Jlle'"~ "~isK',, ata Binding _ . iteR~~-., & ,., . • .. j~d-value data bmdmg allm,s You to d,sp1,y a, omre bble (e,ju,t , si,~,field from Repeate atable). . g1 -value data binding, this type of data binding requires a special control that nlike sm e lJ . !) rts 1t. suPPo . .11 be a list control such as CheckBoxList or ListBox, but it can also be amuch this w1 G·dv· jcallY, trol such as the n 1ew. WP . · ted con . 50 ph1sttca 1 an Display Data in Connected and Disconnected Model. (llore • d contro c pata Bin data bind controls in ASP.NET: · gare foiloWtn Data Bound Control Text Label Button Image Single-item data bound controls DataGrid Datalist ListBox DropDownlistBox Multi-item data bound controls ASP.NET Single Value Data Binding Example Single Value Data Binding Example ILBllll - 0 X
  • 3. Ell: -• • utoEventWiret.Jp="tn.Je" CodeFile="Default.as •• <%@ Page Language- C# A PX.cs" lnhe . - - <html .m•se'lrtlpJ-·"'·""''"'""'rnr> -0,,... <head n.Jnat=="server"> . . . . D I Binding Example by Haider Sir </title> <title> Single Value aa </head> <body> <form id="forrn1" runat==•server"> <div> <table class="style1"> <td class="style3"> <h1>Single Value Data Binding Exarnpie</h1></td> <td class=•style3"> <asp:Label ID="Label1" runat=="server" Font-Size="X-Large" Font-ltalic="False" ForeColor-"#000099" Font-Bold="Tn.Je" Font-Names="AR JULIAN"> User ID:<%# UserlD ¾><br /> UserName: <%# UserName ¾><br /> City: <%# City %> </asp:Label> </table> </div> </form> </body> </html> Default.aspx.cs using System; using System.Collections.Generic· using System.Web.UI; ' using System.Data; using System.Web UI WebCo · · ntrols; public partial class D f { _ e ault :System.Web public int UserlD· public string Use~ame; .UI.Page
  • 4. ~ny; liC str' ~b ed ~id page_Load(object sender, EventArgs e) P'°tsGt ( D:::: 110; userl _•Haider Zaidi"; rr,1arn8 - usB •,Arnroha"; cilY" . oataBind(); 111,s. Single Value Data BindingExample USll ID: DO USEINAMF.: IIAmEl 7Am1 Cm: AMI.OIL - 0 X 0111,1e111 ® ~ = Problems with Single-Value Data Binding 1. Putting code into a page's user interface: One of ASP.NETs great advantages is that it allows developers to separate the user interface code (the HTML and control tags in the .aspx file) from the actual code used for data access and all other tasks (in the code- behind file). 2. Fragmenting code: When using data binding expressions, it may not be obvious where the functionality resides for different operations. Repeated-Value Data Binding Example Default.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" lnherits="_Default" %> :IDOCTYPE html PUBLIC •-t/W3C//DTD XHTML h1tp:/fwww.w3.org/TR/xhtml1 /DTD/xhtml1-transitional.dtd"> 1.0 Transitional/JEN" <htmlxrnlns="http://www.w3.org/1999/xhtml">
  • 5. <head id="Head1• runat="server"> ctitle>asp.net multiple Binding example: using this.DataBind()</title> </head> <body> <form id="form1" runat="server"> <div> <h1 style="color:Navy"> Repeated-Value Data Binding : Example </h 1 > <asp:ListBox 1D="ListBox1• runat="server" BackColor-"#FFCCFF" ForeColor-"#OOOOCC" Font-Bold="True• :> </asp:ListBox> <br /:><br /> <asp:DropDownList 1D="DropDownList1• runat="server" BackColor-"#66FFFF" ForeColor-"#000099" Font-Bold="True" :> </asp:DropDownList> <br /><br /> <asp:RadioButtonList ID="RadioButton1List1• runat="server" BackColor-"#CCCCFF" ForeColor-"#OOOQgg• BorderWidth="2" BorderColor-"Green" Font-Bold="True" > </asp:RadioButtonList> <br /><br /> <asp:CheckBoxList ID="CheckBoxList1• runat="server" BackColor-"#FFFF99" ForeColor="#OOOOSS" BorderWidth="2"
  • 6. 13orde reolor-="lndianRed" Font-Bold="True" 7 •CheckBoXList> ,/~SP· ,/div7 ,~orf117 Jff-lf <Jlltfll7 olt aspi:.cs=--------------- - -------- vefa . . systern; . usin9 collections.Generic; systern- usin9 . . . systern,unq, usin9 • . system.Web, us1n9 u1· . system.Web. , us1n9 Ct 1 • tern Web.LIi.Web on ro s, using sys · I . partial class Default : System.Web.UI.Page pub IC - { protected void Page_Load(object sender, EventArgs e) { l if (!this.lsPostBack) { l Ust<string> DataToolBoxControls = new List<string>(); DataToolBoxControls.Add("Zari"); DataToolBoxControls.Add("Haider"); DataToolBoxControls.Add("Zaidi"); ListBox1 .DataSource = DataTooBoxControls; DropDownlist1 .DataSource = DataTooBoxControls; RadioButton1 List1 .DataSource =DataTooBoxControls; CheckBoxlist1 .DataSource = OataTooBoxControls; this.DataBind(); l
  • 7. -- Repeated-Value Data Binding: Example Toe data source controls include any control that implements the IDataSource interface. Data Source Controk ·, Description Data Source - ,· /taSource Designed to work with SQL Server SQL Server 2000 or later. - databases. It uses Sq! Server .NET / data provider internally. Sql Server .NET data provider classes are defined~ Systern.Data.SqlClient narnespace. ,,ccessDataSource Designed to work with Microsoft Microsoft Access / Access. It uses OleDb data erovider , ~ -:-" OleDb data provider are defined in the System.Data. OleDb namespace. ObjectDataSource Designed to work with objects. Q.bject.l!lsually classes provide a well-define~ ~t.ructure) XmlDataSource Designed to work with XML XML documents documents. . - ---·- ·-- ·-· SiteMapDataSource Designed to work with SiteMap SiteMap ~~ct _§,_ which is a new conceet in - - , .,,.. ASP.NET 4.00 DataSetDataSource Designed to work with QlllaSet ol?j~cts. Di!.L aSet
  • 8. l) AccessOa .· -- '· 1 ~ Obj ... · .:I.Sqq1IDataSource ~; · ectDabdumu: . ,t/:':l . SqlDataSource in Toolbox When you drop SqlDataSource to apage, you will see Configure Data Source link. / Defautaspx.cs)'i>efault.~pr1 1B :SqlDataSource - SqlDataSou;celfCool1lOII SQIData&>urmT• I I Configure Data Source... [configure your data source's settingsJ Configure Data Source Clicking this link launches Configure Data Source wizard, which allows you to configure adata sourc · . _e connection. See Figure below. This wizard allows you to create a new connect10n or use existing co · · dr d 1· nnecllons by selecting from data connection op own 1st
  • 9. Canftfl!!Oatl~-Sqt a.-•...... Slltd•<~lll UMlntle dllJso,ltl, qB [H•l?I.., J DIii dmli IPmidor. l,~.;;-, ..___._; Configure Data Source wizard Clicking New button of Configure Data Source wizard launches Connection Properties wizar~ which allows you to create anew connection.
  • 10. ----------== ; specfythe foilwilo toconn·ecttoSQl Se - - 1 a@ • · rverdati: WJ 1, Select or enter a~~: • prl)l'idef [TOSHIBA-USER ,._______ l~ I I !t . i co~netton ! l ' r@ . Ail 2. Enter nformaooo tll'09on tothe server. 0Use l'{~do:,vs NT Inte!jrated Seauty 0Use aspeciJc user ID and p~d: IJ8f[O: e,2ssword: 1 ! ; ------======-- !3~av em1ti,mvord 3, 0Select or enter agatlbase,n;ime:· [Northwild 0Attic!! adatabase fieasafie -: Fl --------:c-:.-- - ,---~ I ~owse... i I I IIestConnecti>n J Connection Properties Wizard The next dialog of Configure Data Source wizard allows you to specify the variable name of the connection string,
  • 11. - ~ Save c:omedlon stm,i ID the appbtion aMlfiglntion file P111Vide anamefor storing connectionInformation. ... . . • ' ' • • ' " _. , 1 1/-~t~';ii:.-:-,., stoling:comedionstmos'11'f'OUwebstte's-confiQu,iionlie(Web:CO!?fio)easesm~ncfand deploymentofyouia ,:,1· : :; • theconn~onstrtng inWeb:config, entera.n~meinthe boxandthendd!lext.If'/OUchoose not~ dothis, thecoin:~t•,Tosave . savedlq~age'an~rt,-ofthedatasoon:econtrol. ·· ijgij' ... ' •I Do~ wanttosawe thismn~ i.tJtna'.to~• ..i~:mn~ftlel . ., ' •· " ', ' ' ·"~{. 0,I,es.ae th~connecti>n :; ; . "- ~-pCon _ ne_ ~_ trn _g _ l -------::-~ -:~ •·· ~i~-::-;/ --~- :: cancel lL s§ad II l!exl> I' ii] ' Connection String Page ' th SELECT statement Here you can select a The following dialog allows you to specify e I . database table and its columns and add WHERE and ORDER BY c auses.
  • 12. r;.. teme econtrol to getdatafrom the database. tJ d -~likf;bremeve,datafromyour databasei~• ·- IIO;vwau [_ yo . '. ~• - _ _ - - ,. _ _-__~n11sfrom aJilllle orview @ SPev'.co • __ _ ' __ 1 ,/ ~om§QLstatementorstored procedure OSPe v,a· . · 0 ""nS ___________ _ plfof y~w p... . V QuanliyPeJJnit ODiscontinued -·,Eljiroduct!D OUnitPrtce DcategoryName DR~tum on~u n ~u erows , I'.]productName OUnits!nStock [ WHERE Elsupplier!D OUnitsOnOrder I 0category!D OReorderlevel OBJ)ER BY __ -,-----:-_____________J [ A dyanced Options... !;ElECT-Statement [ cancel 11 <Jlack ]I Next > I.___ Ffl=---i;,r, -·_ Configure Select Statement Dialog The next dialog tests the data.
  • 13. til· ~ - .f.f¥.t!'94' . - • • sIDataSource1 . Configure Data Source · Q Test(!uely Execute the selectstarement to previewtheresult - T completethis wiZard, did< Rnlsh. . e did rest Query, 0 To preview thedata returned bythis data soorr ' IUntl'rice IUnits!nStocklUnitsOnOrderl1. -!' .,i I5uppierlllIcitegorylllIQuantlyi'erJnt 39 0 liLJ ProductJDIProductName 1 Ii 1oboxesx20bags 18.0000 I Olai 1 1 24. 12 oz bottles 19.0000 17 K O 2_ 2 Oiang I 70 ; 1 2 12 . 550 rn bottles 10.0000 13 3 Mi.eed Syrup I 0 C 1 2 48 -6 oz jars 22.0000 53 OiefAnton's Cljun Seasonil0 2 4 1 2 12 -8 ozjars 25.0000 120 0 2 Grandma's so~nberrv Spread p 6 1 7 12 •1bpkgs. 30.0000 15 0 1 unde Bob's oroani: Dried Pears 7 /2 12•12 oz jars 40.0000 6 0 : er. 8 Northwoods eranbell)' Sauce 3 J. _ . dl~ I. - ~.- .. .. T $·,1 . ml [ Jelt Quel'( I SflfCT Statement 58.f{T • FROM [At>habeti:al1st of products] - . -- - -- - [ cancel ][ <!lack ]_ k"1.1:--;- [ [flish I Test Query Dialog Now this entire action adds the following code to the HTML file: <asp:SqlDataSource ID="SqlDataSourcel" Runat="server" SelectCommand="SELECT * FROM [Alphabetical list of products]" ConnectionString="<$ connectionStrings:AppConnectionStringl >"> </asp:SqlDataSource> Ifyou do not have Visual Studio, you can create SqlDataSource control in HTML by editing the HTML code. As you can see from this code, tag <asp:SqlDataSource> represents the SqlDataSource control and like other controls, you can set its parameters in HTML file. The above code sets SelectCommand and ConnectionString parameters of SqlDataSource control. You can also set the controls parameters from Properties window. As you can see from Figure Connection string page, you can set various properties of SqlDataSource including ConncctionString and SelectQuery.
  • 14. pg SqlDa~ . _Itel Syste m .Web ~fWjJ§J .UJ.Webc~ ntrols.SqlDataSource . - I(Expressions) .- . [ea~ ISqlDatiSoun:el -- - JCacheExpirationPol lnmite - ~ Icy~ - ,....,,,.,,,., ""'"' eance15~~l -- :~ IOverwrn:eChanges . ~ - ill1 Se.rver=TOSHIBMJSER;IntegrateJ!_ ,· - IDataSet ,,!DeleteQuery ( :;i - - Query) "]EnableCaching Fls .. a e . !~~~ leVieWState 'I True :J Rlter£xpression I jRlter?arameters I(Colection) r•"l"•• 'Iq,..,J Ol~ aluesParameterFormatstring Ioriginal_{0} ProviderName I ~eiectQuery . (Query) ISortParameterName ! Sq!CacheDependency _1 UpdateQuery (Query) SelectQuery Select Query SqlDataSource Properties If you InsertQuery property, it launches Command and Parameter Editor, where you can add and remove parameters. See Figure Configure Select Statement dialog. From this dialog, you can also launch Query Builder, which allows you to create a SQL query.
  • 15. sa.ECT~ommand: ~CT • FROM [~abeto1st ofproducts] Refregi .J f~15l · Name I vaie- ifw,;:,;. ·,:;::: t . ·, [ Command and Parameter Editor l. What is data binding? Explain its different types with example. 2. Explain problem with single value data binding with example. 3. Explain different data source ofADO.NET.