This document provides an overview of data binding in ASP.NET, including single-value and repeated-value binding. It discusses using the SqlDataSource control to bind database data to web controls. The SqlDataSource allows configuring a data connection through a wizard that specifies the connection string, SELECT statement, and tests the query. This binds the database data to controls like ListBox and DropDownList for display on the web page.
+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">
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.