Vous êtes sur la page 1sur 166

:

IIS .Net Framework


ASP.NET

:
IIS

ASP.NET . .Net Framework .


IIS Home

. IIS

www.pupuol.com


: IIS
IIS

.
. Add/Remove Programs

Add/Remove windows components .

Windows ) Internet Information Services (IIS


Details .

Next IIS ) CD ( .
) . (

- . IIS

www.pupuol.com


IIS :

: Documentation .

) : File Transfer Protocol (FTP .


: Front-page Server Extensions
.

: Internet Service Manager .


: NNTP Service Network News .

: SMTP Service .

- . IIS
IIS Administrative tools Internet Service
Manger .

www.pupuol.com


: .Net Framework
IIS ! IIS
.Net Framework ! IIS .
.Net Framework :

. Setup


. Next !

IIS : ASP.NET
( : Home
Home Root

. IIS .
C:\Inetpub\WWWROOT IIS .
Internet Service Manager Administrative tools
) .( Default web site

. Default web site properties . Tab Home


Directory ) ! ( ) .(

User

. Read Browsing
.

www.pupuol.com

- .
Home :
: A directory located on this computer .

: A share location on another computer


Home .

: A Redirection to a URL
. www.dot.tk .

www.pupuol.com

( : IIS
(C:\Inetpub\WWWROOT) Home
. Test

) ( C:\Inetpub\WWWROOT\Tools :
http://localhost/test

www.pupuol.com

Home . C:\MyDir
.
.

- Home . IIS

Internet Service Manager . Action

New Virtual Directory .


Default Web Site .

www.pupuol.com


Next . .

www.pupuol.com

- .

www.pupuol.com

:
Windows Explorer
Tab

Properties

.
web sharing

Edit Alias

Share
Ok
.

Internet Service Manager


.

www.pupuol.com

delete

- .

: Read
) . (

www.pupuol.com


: Run Scripts .
ASP ) .
(
: Execute .
ASP
.

: Browse

.
. Default Document

.
:

Home

.
IIS

Default Document : IIS


Default document IIS


.
IIS . IIS
Browsing
Error .

www.pupuol.com


Index.htm, :

Default.aspx .

Internet Service Manager . Default website

Tab Document Enable default document .


.
:

Tab Document Default web site


Document footer .
. HTML >. <bold> Copyright 2003</bold

- .

www.pupuol.com

. Pause .

. .

ASP.NET Pause

- .
:
. :
.

iisreset /restart

iisreset /start

iisreset /stop

iisreset /reboot

iisreset /rebootonerror

.
.
.

iisreset /status
?iisreset /

www.pupuol.com


: SubWeb
.

Front-page Server Extensions

LocalHost IIS

Server extension web . .


.
title . Next
Next ! .
SubWeb root web .

http://www.microsoft.com/frontpage/wpp/serk
FrontPageServer
WinXP . Win2000 advanced server.

- FrontPageServer

www.pupuol.com


:
- Ch01 .

D:\ASP_NET\Chapter01 .
SubWeb

www.pupuol.com

:
C#
ASP.NET

:
C# ASP.NET .

.
.

): (NameSpaces
.
.

.
. :

www.pupuol.com


namespace anyName
{
.
Class anyClassName
{
..
}
.
}

System .
:
;using System

public .

ProjectName.NameSpace.ClassName.MemberName

:
;)System.Array.Sort(strArray

;using System
;)Array.Sort(strArray

: NameSpace
.
New Project
ASP.NET . Project Visual C# Project
ASP.NET Web Application . Location

www.pupuol.com


Home
. Ok
) . (

- ASP.NET VC#

www.pupuol.com

- VS.NET .
ToolBox Label ) (Button ) .(

- .


. Code Behind
.

www.pupuol.com


" !

! " .
.
- string strText .
.

- ) " " ( .
- . C#
.

- Text .

Label1

) . ( Text

)
( .

- autocomplete

... .

- F5 .

. Address Bar

www.pupuol.com

- .

. :

- Tab WebForm1.aspx .
Document
. charset Unicode
) (UTF-8 ) . (

- ! save as . save
. ) .(

Save with encoding

Encoding ) Unicode ( UTF-8 with signature .


!

) . advanced save options


(

www.pupuol.com

- charset .

- .

www.pupuol.com


:
:

. .

. C# //

) (C++ C /* .. */ .

autocomplete

.
)!( ....
>///<summary
///
///
>///</summary

:
. C#

.

www.pupuol.com


:
. property
.
) (string .

DateTime . Today

. .
.

.
; System.DateTime.Now System

: C#

.
.

][ chrData ] chrData[0
] chrData[9.

- .
;]String[] strData = new string[2

www.pupuol.com


-
;} "string [] strData = { "1234","abcd

.
.
-
;"strData[0] = "1234
;"strData[1] = "abcd

Array .
Sort .
for foreach

)for( int i=0 ; i< strData.Length ; i++


!do some things

) ( .

Array TextBox .

TextMode

www.pupuol.com


MultiLine .

source . forum
.


C
. .

. DateTime
ToLongDatastring .

class myClassName
{

public private

) void (
. { } .
:
) public int myFunc( int x
{
....
}

www.pupuol.com


overloading .
:
AnyType propertyName
{
;get
;set
}


)
(.

substring Project Add Class

VS.NET .

public private .


private .

www.pupuol.com


C# !

) : ( Thinking in C#
www.thinkingin.net
www.BruceEckel.com

.
C# .

WWWRoot classes
Chxx xx .

.
.

www.pupuol.com

- ASP.NET VS.NET .

.
TextBox .

www.pupuol.com

:
HTML ASP.NET

:
HTML HTML
. ) HTML HTML (
HTML HTML .
!

.
VS.NET
. DHTML
VS.NET .


HTML System.Web.UI.HtmlControls .
HTML " RUNAT="Server .
.

www.pupuol.com


HTML ID
.
HTML HTMLInput HtmlForm
.
HTMLForm .

form HTML " RUNAT="Server


.

VS.NET ) ( ASPX
) ( .

VS.NET .

Method . GET
URL HTTP
Post .

www.pupuol.com


VS.NET .

Disabled False True


.

Action ASP.NET .

ASP
.

HTML
- : - .

. ToolBox

Tab .

Tab HTML . Visual InterDev


Tab !
Tab ) (Button
. .

) (VS.NET Design

HTML ) .( HTML VS.NET


.

- . VS.NET

www.pupuol.com

> <Input Type .

Button ) ( . Submit

Reset
. " RUNAT="Server

.
HTML JavaScript .

" RUNAT="Server Run as

server control ) . ( Code

Behind ServerClick .

- HTML .

www.pupuol.com


> <Button

Type Image
onMouseOver onMouseOut
.

Image

. ALT ToolTip
.

Type Text TextBox


Password TextBox .
TextBox MultiLine TextArea
.
Boolean CheckBox

Checked True .

RadioButtons
RadioButton . ID
Name .

Radio[0].Checked .
DropDown List RadioButton
. Bind DatSource DataBind

. SelectedIndex

www.pupuol.com


. Multiple
True.

Anchor Tag > <a HRef


.
Upload
.

HTMLInputFile Upload.

form HTML

" Encrypt="MultiPart/form-data .

Upload
. > <Input File " Type="File .
" RUNAT="Srever . Submit

.
;)(fileSuggestionsControl.PostedFile.SaveAs

\\ \c:\temp

\\c:\\temp

www.pupuol.com


) (
.

Submit
.
VS.NET HTML
TextFiled ) Button . (

-
Label

. ID Pass .

Properties ID txtID txtPass


ID . btnSubmit
.

www.pupuol.com


Send . Value Send

. txtPass Password ) ( .

Run as server control .

Code

Behind .
)private void btnSubmit_ServerClick(object sender, System.EventArgs e
{
) "if (txtID.Value =="a" && txtPass.Value =="b
;)"!Response.Write("Ok
else
;)"!Response.Write("Try again
}

ASP Response .

HTML.

calc MessageBox
DropDown List .

www.pupuol.com


TextFiled DropDown List ) Id . (

Id btnCalc txtNo Id DropDown ddlNo2 .


HTML .

- .
Head > </Head .
Insert script block Client ) .(
.
Client Objects & Events

btnCalc ) . (
. onClick
) . (

www.pupuol.com

- .


btnCalc_click .
VS.NET

!
.

")(language="javascript" onclick="return btnCalc_onclick

www.pupuol.com

- .

- .

onload dropdown list .

window
onload .

window_onload body

>")(<body MS_POSITIONING="GridLayout" language="javascript" onload="return window_onload

www.pupuol.com

dropdown list
. ) (

dropdownlist
option :
;)newOption = new Option(optionText,optionValue,defaultSelected,selected

- dropdown list .

www.pupuol.com


:
{ )(function window_onload
;var i,j=0
)for(i=0 ; i<=100 ; i+=10
{
;)dd = new Option(i,i
;window.Form1.ddlNo2.options[j]=dd
;j++
}
}

:
{ )(function btnCalc_onclick
;) window.alert( window.Form1.ddlNo2.value * window.Form1.txtNo.value
}

- - ( . -

www.pupuol.com


:
- HTML
TextArea TextArea .

TextField .
document.write .

- Upload
) . : System.Guid ( .

www.pupuol.com

:
ASP.NET

:

ASP.NET .
.

: Layout
:

) : Grid Layout ( .
.

: Flow Layout .

www.pupuol.com

Document
PageLayout ) .(

- Layout .

:
HTML .

www.pupuol.com

HTML


- . HTML

Server Controls

HTML Controls

.NetFrameWork

HTML

: HTML

ASP ASP.NET . ASP


HTML HTML .
.
HTML
) (

ToolBox
.

www.pupuol.com


.HTML -
Server Controls

Label, TextBox, Literal

Button, ResetButton,
SubmitButton
Button, ResetButton,
SubmitButton
Image

DataGrid, Table
ListBox, DropDownList,
Repeater, DataList
Button, LinkButton,
ImageButton
CheckBoxList, CheckBox,
RadioButtonList, RadioButton
ImageButton, Image

( <a> ) -

HyperLink

FlowLayout, GridLayout

Placeholder, Panel

Calendar

AdRotator

Horizontal rule

Literal

FileField

RequiredFieldValidator,
ComareValidator,
RangeValidator,
RegularExperssionValidator,
CustomValidator,
ValidationSummury

HTML Controls
Label, TextField,
TextArea, PasswordFiled
Table
DropDown, ListBox

Input Hidden

www.pupuol.com

:
.

;)"Response.Write("Some Text

Label
TextBox ReadOnly True
Literal

TextBox .

- TextBox

Text

TextMode

SingleLine MultiLine TextArea

ReadOnly
AutoPostBack

Password
True .
True TextChanged
False.

www.pupuol.com

. DropDownList ListBox ) (Table

. DataList DataGrid Repeater

.
.

- . ASP.NET

ListBox

Scroll

DropDownList Dropdownlist
Table

DataGrid

:
DropDownList ListBox Table
.

Collection Editor DropDownList ListBox

) .(

ListBox DropDownList Items

) .(

www.pupuol.com


Rows

- Items Collection
Editor ListBox DropDownList .

www.pupuol.com

- Collection Editor ListBox


.

:
Add Items .
;)ListBox.Items.Add(.

Table .

.
.
) .(

www.pupuol.com


:
Table TextBox DropDownList
txtAdd ddlItems btnClick tblEx01 .

. TextBox

Add DropDownList Table )


( .

- .

:
SelectedItem .

.
ddlItems.SelectedItem.Text

www.pupuol.com


Data Binding :
.
. :
:
- DropdownList . arrData
.

DropDownList - DataBinding
) ( .

- DataSource Custom Binding Exp


arrData .

- .

- DataBinding . DropDownList

www.pupuol.com

- arrData Bind
. DropDownList

:
DataBinding
. DataBind

. EnableViewState False.

www.pupuol.com


DataList DataGrid : RepeaterControls
data binding .
Templates . Template
HTML .
.
- . data source

- Bind .
- Templates HTML
Grid .

- Grid bind
.

:
Template DataGrid Bind

- ) ( .
.

- DataGrid .
- Template Property Builder )
. .(

- Columns Template
(<) Add .

Template Ok ) .(

www.pupuol.com


- DataSource )
( ) arrData .(

- DataGrid ) Columns(0 pop-up .


Edit ) .(

- Property Builder . DataGrid

www.pupuol.com

- Template .

) ( .

www.pupuol.com

- ] Columns[0 .
.

- Template Drag

DataGrid ) Cut/Paste ( . TextBox


) Drag Columns(0 ) . (

- DataBinding ) TextBox
template ( ) ( .

- Bindable .
Text Simple Binding Container

DataItem .
Ok .

www.pupuol.com

- TextBox ] Columns[0 .

- Binding .

www.pupuol.com

- Template . DataGrid
) Columns(1 pop-up .

- . Drag
) Columns(1 Template . DataGrid

- ] Columns[1 .
Template - .
End Tempalate editing pop-up .

- .
Template .

www.pupuol.com

- .

:
LinkButton Button ImageButton .
Post-Back .
.

ListBox TextBox Button ) AutoPostBack .(


True . Page_Load

. .

www.pupuol.com


private void Page_Load(object sender, System.EventArgs e)
{
Response.Write("Page load.<br>");
if ( ! Page.IsPostBack ) // run 1 time
{
ListBox1.Items.Add("1");
ListBox1.Items.Add("2");
ListBox1.Items.Add("3");
}
}
private void TextBox1_TextChanged(object sender, System.EventArgs e)
{
Response.Write("Text changed.<br>");
}
private void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
Response.Write("Item selected.<br>");
}
private void Button1_Click(object sender, System.EventArgs e)
{
Response.Write("Page load.<br>");
}

www.pupuol.com

.
Button LinkButton . ImageButton
. x y

ImageMaps .

:
CheckBox RadioButtonList RadioButton CheckBoxList

. ListBox DropDownList

www.pupuol.com


Collection RadioButtonList CheckBoxList
. Items .

Checked CheckBox RadioButton

RadioButton RadioButton

OptionButton . GroupName
radioButton .

CheckBoxList RadioButtonList foreach

. Selected
.
:
RadioButtonList.
RadioButtonList . Items

. ) .(

www.pupuol.com

. RadioButtonList

- .

www.pupuol.com


:
)private void Button1_Click(object sender, System.EventArgs e
{
) foreach ( ListItem lstItem in RadioButtonList1.Items
{
) if ( lstItem.Selected
;)">Response.Write(lstItem.Text + " is selected.<br
}
}

:
.

- : BackGround
. BackImageURL Panel
.

- : foreground Image
ImageURL .

- : . ImageButton

- : AdRotator
.

ASP.NET . AdRotator
XML
. XML

.
AdRotator XML
.

www.pupuol.com


: AdRotator
. AdRotator -

. XML -
TargetSchema -
. AdRotator Schedule file

< Ad> -
. XML < Advertisement>

. XML -
XML AdvertisementFile AdRotator -
.
. XML
<Advertisements>
<Ad>
<ImageUrl>./SampleBanner.gif</ImageUrl>
<NavigateUrl>http://www.google.com</NavigateUrl>
<AlternateText>Cick me now!</AlternateText>
<Keyword>ShowMe</Keyword>
<Impressions>71</Impressions>
</Ad>
<Ad>
<ImageUrl>./AnotherSample.gif</ImageUrl>
<NavigateUrl>http://www.microsoft.com</NavigateUrl>
<AlternateText>Go to Microsoft Site</AlternateText>
<Keyword>ShowMe</Keyword>
<Impressions>70</Impressions>
</Ad>
<Ad>
<ImageUrl>./DoesNotExist.gif</ImageUrl>
<NavigateUrl>http://www.microsoft.com</NavigateUrl>
<AlternateText>Won't see me</AlternateText>
<Keyword>DoNotShowMe</Keyword>
<Impressions>2000</Impressions>
</Ad>
</Advertisements>

www.pupuol.com


- . AdRotator
Tag

><Ad

Ad .

><ImageURL

><NavigateURL

.
ToolTip

><AlternativeText

><Keyword

Ad .

><Impression

Ad .
.

:


.

Panel . .

Drag .

FolwLayout Space Enter

www.pupuol.com


:
.

SelectionChanged SelectedDate
. SelectedDates SelectionChanged post-back

www.pupuol.com


:
- ImageButton
) ( .
.

- AdRotator
.

- Panel .
.
.
.

- Label
.

www.pupuol.com

:
.

:

:
) ( .
.

ASP.NET

www.pupuol.com


WebUIValidation.JS

.
) Jscript

(
.

ControlToValidate
.

- . ASP.NET

RequiredFieldValidator
CompareValidator
RangeValidator
RegularExpressionValidator
CustomValidator
validationSummary

) .
(

.

.

.

.

.

www.pupuol.com

-
ControlToValidate .
CompareValidator ControlToCompare .

- ErrorMessage
.

- Text .
ErrorMessage .

- ValidationSummary
.

- Post-Back
. ) (
.
MessageBox
ValidationSummary ShowMessage True.
RegularExprssionValidator
ValidationExpression -

www.pupuol.com

- . RegularExprssionValidator
Pattern-matching )
MSDN (.

:
. TextBox
RequiredFieldValidator
RegularExpressionValidator .
CompareValidator :

ControlToValidate Invalid .

ControlToComare Valid . .

www.pupuol.com


CompareValidator Operator

.
. .

:
- TextBox Label Button .
TextBox TextBox Label
.

.
TextBox ) ( txtVal1 txtVal2 btnCalc Label
lblResult .

TextBox

TextBox
RequiredFieldValidator RangeValidator
) .(

- .

www.pupuol.com


ControlToValidate RequiredFieldValidator
txtVal1 ) ( RequiredFieldValidator
TextBox txtVal2 .

- ControlToValidate . RequiredFieldValidator

RangeValidator ControlToValidate txtVal2

min max ) .(

ErrorMessage .

) .(

( .

www.pupuol.com

- . RangeValidator

- ErrorMessage .

TextBox

RangeValidator .! ! Type
int ) . (

www.pupuol.com

- RangeValidator .

:

!
Post-Back Submit HTML Control .

) IsValid

( Page

www.pupuol.com

- .

Validation

TextBox txtID RequiredFieldValidator TextBox

. btnSend HTML Submit


btnCancel ) .(

) Project ( Add web form

. Label . Sorry! :

HTML Submit :
"<INPUT style="Z-INDEX: 101; LEFT: 274px; WIDTH: 115px; POSITION: absolute; TOP: 142px; HEIGHT: 27px
>";type="submit" value="Cancel" id="btnCancel" language="javascript" onclick="Page_ValidationActive=false

:
)private void Page_Load(object sender, System.EventArgs e
{
) if ( Page.IsPostBack
{
;)(Page.Validate
//user cancelled the validation
) if (! Page.IsValid
; )"Response.Redirect("WebForm2.aspx
}
}

www.pupuol.com

! Sorry ! ) (...

CustomValidator .
ServerValidate .
ClientValidationFunction .

:
.

btnTest TextBox txtPrime


CustomValidator vldtxtPrime ) . (

-
ControlToValidate vldtxtPrime btnTest .
vldtxtPrime .

www.pupuol.com


) . ( ServerValidate .
:

private void vldtxtPrime_ServerValidate(object source,


)System.Web.UI.WebControls.ServerValidateEventArgs args

- . CustomValidator
.
.

) ErrorMessage ( .

www.pupuol.com

: ASP.NET
ASP.NET

- ASP.NET

HyperLink

;)(Response.Redirect

HyperLink .

;)(Server.Transfer


. ) (.aspx
.

;)(Server.Execute

. .
.


;)(window.open

.
pop-up stopper
.

www.pupuol.com


HyperLink : Redirection
NavigateURL HyperLink

. LinkButton
ImageButton . Response.Redirect

: Transfer
HyperLink Redirect

Transfer :
. Transfer True

QueryString ViewState .

EnableViewStateMac false . ASP.NET

ViewState Hash . False


.

Request.Form . ASP

ASP.NET
) ! (.
: Transfer Execute .
HTML .

www.pupuol.com


:
. .
.
TextBox btnSend txtSend .

; )Server.Transfer("WebForm2.aspx",true

Label lblReceive

Page_Load :

; )(lblReceive.Text = "Received from WebForm1: "+ Request.Form["txtSend"].ToString

) EnableViewStateMac False . HTML


.
True False HTML
. ( .
"<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false
>Inherits="ex04.WebForm1" enableViewState="True" enableViewStateMac="False"%

www.pupuol.com


: Execute
Execute .

.
Transfer EnableViewStateMac False.

Execute Post-Back

.
Post-Back .

:
window.open .
:
Window.Open( "http://www.wrox.com/", "myWindowOne",
;) ""toolbar=no, menubar=no, location=no, directories=no

Target HyperLink
.

www.pupuol.com


:
- window.open
encapsulate . .

- ValidationSummary .
- CompareValidator
.

- .
- Server.Execute .

- URL window.open

www.pupuol.com

:
SQL SQL-Server
) (

:
ASP.NET

SQL-Server
ASP.NET SQL

SQL-Server ) ( .

www.pupuol.com


.
SQL-Server .

Advanced Server SQL-Server


pro

win2000 Pro

XP

SQL-Server Desktop Edition .

:
.
. SQL-Server Enterprise

manager DataBases ) .(

Ok .

SQL-Server
.

) (

) .( Null
.

. ( .
:
. ID, Pass, Name_LastName
.

www.pupuol.com

- . SQL-Server

www.pupuol.com

- . SQL-Server

www.pupuol.com

- . SQL-Server

- .

www.pupuol.com


:
-
n n . national.

- ) (
Allow Null .

.

.

- Name . TextBox

MaxLength
.


. .

-

. // . //

- SQL-Server tbl _ t
.
SQL-Server ) (.

- Primary key

) . ( .

SQL-Server

-
Foreign key . Foreign key Primary key

www.pupuol.com

- Primary Key )

( .

- Primary key .

SQL-Server .

Open Table Return all rows

www.pupuol.com


) .( ) ( .
.

SQL

. Open Table Query


) .(

- .

- Return all rows .

www.pupuol.com

:
) t_band

( :

[band_id] [int] IDENTITY (1, 1) NOT NULL


[band_title] [varchar] (100) NOT NULL
[music_type_id] [int] NOT NULL
[record_company_id] [int] NOT NULL

Normalized

Normalization .
.
Normalization forms . :
): (FNF

. .

www.pupuol.com

- . SQL-Server

): (SNF
entire key . Primary key
.
):(TNF
.

Foreign key )
( .

www.pupuol.com

Join .
!

: Query Analyzer
Enterprise manager
Query Analyzer SQL-Server
T-SQL .
Query Analyzer SQL-Server
) .( SQL-Server LoginName=sa

( . Query Analyzer . Enterprise


manager Tools Query Analyzer .

) .(

F5 .
:
USE master
GO
CREATE DATABASE Music ON PRIMARY
( NAME = MusicData,
FILENAME = C:\MSSQL7\data\MusicData.mdf
)

www.pupuol.com


USE Music
GO
CREATE TABLE [dbo].[t_bands] (
[band_id] [int] IDENTITY (1, 1) NOT NULL ,
[band_title] [varchar] (100) NOT NULL ,
[music_type_id] [int] NOT NULL ,
[record_company_id] [int] NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[t_bands] WITH NOCHECK ADD
CONSTRAINT [PK_t_bands] PRIMARY KEY NONCLUSTERED
(
[band_id]
) ON [PRIMARY] ,
CONSTRAINT [IX_bands_title] UNIQUE NONCLUSTERED
(
[band_title]
) ON [PRIMARY]
GO

. Query Analyzer SQL-Server -

www.pupuol.com

. Query Analyzer
.

: View
View SQL-Server
View . ) (Query View .

) View ( Query
. View Query analyzer Enterprise Manager
.

:
CREATE VIEW [owner.]view_name
AS select_statement

View bands
t_babds .

www.pupuol.com


USE Music
GO
CREATE VIEW all_bands
AS
SELECT * FROM t_bands

: Stored procedures
T-SQL .
View .
.
:
CREATE PROCEDURE procedure_name
]][{@parameter_name data_type} [VARYING] [= default] [OUTPUT
][, ...n
AS
sql_statement

:
CREATE PROCEDURE pr_albums
AS
SELECT album_title FROM t_albums ORDER BY album_title

Query analyzer ) Exec

( Execute F5 .

www.pupuol.com

CREATE PROCEDURE pr_albums2


@iBandID INT
AS
SELECT album_title
FROM t_albums
WHERE band_id = @iBandID
ORDER BY album_title

: Triggers
Trigger invoked
Triggers .

.

delete .

Trigger .

Update Insert Delete / .


:

CREATE TRIGGER trigger_name


ON table_name
}FOR {INSERT | UPDATE | DELETE
AS sql_statement

www.pupuol.com

CREATE TRIGGER trg_DeleteBand


ON t_bands
FOR DELETE
AS
IF EXISTS(SELECT album_id FROM t_albums, deleted WHERE t_albums.band_id
=
deleted.band_id)
BEGIN
RAISERROR(Band has albums!,16,1)
END

www.pupuol.com


:
- t_band
Query analyzer .

www.pupuol.com

:
SQL SQL-Server
) (

:
SQL

.
forum .

.
.

SQL
Query Analyzer .

: Select
SQL select .

.
.

www.pupuol.com


: Insert
Insert
) ( .

. Insert
) (

:
)INSERT INTO tablename [(columnname, ...)] VALUES (constant, ...

SQL-Server
Pubs .
.
. Enterprise manager
) . (

- Discounts Pubs . SQL-Server

www.pupuol.com


Tools SQL Query analyzer
SQL .
Pubs )
. ( Use SQL-Server .

- .

:
use pubs
) insert into discounts ( discounttype , discount ) values ( 'myt1' , 5
select * from discounts

Ctrl+F5
F5 .

' '

AllowNull

. .

www.pupuol.com


ADO.NET
.

: Delete
Delete ) (
:
]DELETE FROM tablename [WHERE where expression

where ! )

! ( . Where
And Or
.
.
Query analyzer .
use pubs
select * from discounts
delete from discounts where discounttype='myt1' and discount = 5
select * from discounts

SQL-server discounts)(

www.pupuol.com


Predicate Where
. Null Like Contains
)( true Contains

true Like .
. _ % Wildcards .
: Query analyzer

use pubs
insert into discounts ( discounttype , discount ) values ( 'myt1' , 5 )
insert into discounts ( discounttype , discount ) values ( 'myt12' , 5 )
insert into discounts ( discounttype , discount ) values ( 'myt123' , 5 )
select * from discounts where discounttype like 'myt%'
delete from discounts where discounttype like 'myt12%'
select * from discounts

: Update
update ) (
:
UPDATE tablename SET columnname = contstant [AND columnname =
constant ...] [WHERE where-expression]

. Where

www.pupuol.com


Query analyzer :
use pubs
) insert into discounts ( discounttype , discount ) values ( 'myt1' , 5
select * from discounts
'UPDATE discounts SET discounttype = 'aaa' WHERE discounttype='myt1
select * from discounts

'discounttype='myt1

aaa

) (Forum :
.
!

:
-

) tblUsers

(

www.pupuol.com


) tblPosts
(

-
-
-

-
-
-

) tblArea (

!
PM
emoticons


....

www.pupuol.com

- .

- Authors Pubs SQL-server


Phone
) (.

- Query analyzer .
- City ZipCode
Tehran !
- ng
.

www.pupuol.com

:
- ASP.NET

:
VS.NET ADO.NET
. ADO.NET
Connection
.

: ADO.NET
ADO.NET :
: OLE SQL XML
.

www.pupuol.com


: Connection Command
.

: Data Set . Data


Set .
Disconnected Data Set .
- ADO.NET .

Connection
Object

Data store
)(OLE DB, SQL, DB, XML
DataSet
Object

DataAdapter
Object

- Connection Command . ADO.NET

ADO.NET :
OleDbConnection . Ole
OleDataAdaptor .

SqlDbConnection .

ADO.NET

www.pupuol.com


- : ADO.NET

Data Sets

System.Data

System.Data.SqlClient

SQL-Server

System.Data.OleDb

OLE


Import :

;using System.Data
//
;using System.Data.SqlClient
// OLE DB
;using System.Data.OleDb

ADO.NET :
- .
- DataSet . Adapter

- DataSet .

- DataSet . Adapter
- - Open
. Open
.

www.pupuol.com

- ADO.NET .

www.pupuol.com

- : - .
.

ConnectionString

: SQL-Server
DataGrid .
Paging

.
.
SQLDataAdapter SQLConnection : . SQLDataSet

SQLConnection System.Data.SqlClient

SQL-Server . SQLDataAdapter
. SQLDataSet

System.Data SQLDataAdapter
SQL-Server .

www.pupuol.com



SQL-Server Pubs Titles
DataGrid .
System.Data System.Data.SqlClient . DataGrid

. :

SqlConnection . ConnectionString
ID Pass
.
SqlConnection sqlconnectionPubs = new
;)"SqlConnection("server=(local);uid=sa;pwd=;database=pubs

SQLDataAdapter SQL

DataSet :

SqlDataAdapter sqldataadapterTitles = new


(SqlDataAdapter
"select title, notes, price from titles where type='business'",
;)sqlconnectionPubs
;)(DataSet datasetTitles = new DataSet
;)"sqldataadapterTitles.Fill(datasetTitles, "titles

SQLDataAdapter DataSet DataSource .


DataSet .
;DataGrid1.DataSource=datasetTitles.Tables["titles"].DefaultView
;)(DataGrid1.DataBind

www.pupuol.com


: SQL-Server

Insert SQL

SQL Command

. Insert

:
tblUsers AspNetForum

use AspNetForum
CREATE TABLE [dbo].[tblUsers] (
[user_id] [int] IDENTITY (1, 1) NOT NULL ,
[user_type_id] [smallint] NULL ,
[user_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[email] [varchar] (60) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[password] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[addr1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[city] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[state] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[postalcode] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[country] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[phone] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[fax] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[signature] [varchar] (1024) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
) ON [PRIMARY]
GO

www.pupuol.com

- . Table HTML Controls


.

ReqiuredFieldValidator .

Table

) (Border .

user_id Auto Increment SQL-Server

user_type_id

. .

DataGrid

www.pupuol.com


:
using System.Data.SqlClient;

: Connection
SqlConnection sqlconnectionForum = new
SqlConnection("server=(local);uid=sa;pwd=;database=AspNetForum");

SQL SQLDataAdapter
.

SqlDataAdapter sqldataadapterUsers = new


SqlDataAdapter("select * from tblUsers", sqlconnectionForum);

: Insert
String insertCmd =
"INSERT INTO tblUsers(user_type_id, user_name, email,"+
"password, addr1, city, state, postalcode, country,"+
"phone,fax,signature) VALUES("+
"0,"+
txtName.Text.Trim() +","+
txtEmail.Text.Trim()+","+txtPassWord.Text.Trim()+","+
txtAddress.Text.Trim() +","+
txtCity.Text.Trim()+","+txtState.Text.Trim()+","+
txtPostalCode.Text.Trim() +","+
txtCountry.Text.Trim()+","+txtPhone.Text.Trim()+","+
txtFax.Text.Trim() +","+ txtSig.Text.Trim() + ")";

: SQLCommand
SqlCommand sqlcommandUsers = new
SqlCommand(insertCmd, sqlconnectionForum);

. Execute Open Command


sqlcommandUsers.Connection.Open();
sqlcommandUsers.ExecuteNonQuery();
sqlcommandUsers.Connection.Close();

www.pupuol.com

;)(DataSet datasetUsers = new DataSet


;)"sqldataadapterUsers.Fill(datasetUsers, "tblUsers
;DataGrid1.DataSource=datasetUsers.Tables["tblUsers"].DefaultView
;)(DataGrid1.DataBind

:
SQL Update
.

Insert


Pubs Title_ID titles BU9999

35.00 .
:

;using System.Data.SqlClient

Pubs :
SqlConnection sqlconnectionPubs =new
;)"SqlConnection("server=(local);uid=sa;pwd=;database=pubs

www.pupuol.com


SQLDataAdapter SQL
.

= SqlDataAdapter sqldataadapterTitles
new SqlDataAdapter("select title, notes,"+
;)"price from titles where type='business'", sqlconnectionPubs

Insert
SQLCommand :
= String updateCmd
;"'"UPDATE titles SET price = 35.00 WHERE title_id = 'BU9999
= SqlCommand sqlcommandTitles
;)new SqlCommand(updateCmd, sqlconnectionPubs

Command Execute Open .


;)(sqlcommandTitles.Connection.Open
;)(sqlcommandTitles.ExecuteNonQuery
;)(sqlcommandTitles.Connection.Close

:
;)(DataSet datasetTitles = new DataSet
;)"sqldataadapterTitles.Fill(datasetTitles, "titles
;DataGrid1.DataSource=datasetTitles.Tables["titles"].DefaultView
;)(DataGrid1.DataBind

:

.

SQL

SQLConnection .

SqlCommand SQL .

www.pupuol.com


:
BU9999 title_id Pubs Titles
.
:
private void Page_Load(object sender, System.EventArgs e)
{
SqlConnection sqlconnectionPubs = new
SqlConnection("server=(local);uid=sa;pwd=;database=pubs");
SqlDataAdapter sqldataadapterTitles = new
SqlDataAdapter("select title, notes,"+
"price from titles where type='business'", sqlconnectionPubs);
String deleteCmd =
"DELETE FROM titles WHERE title_id = 'BU9999'";
SqlCommand sqlcommandTitles =
new SqlCommand(deleteCmd, sqlconnectionPubs);
sqlcommandTitles.Connection.Open();
sqlcommandTitles.ExecuteNonQuery();
sqlcommandTitles.Connection.Close();
DataSet datasetTitles = new DataSet();
sqldataadapterTitles.Fill(datasetTitles, "titles");
DataGrid1.DataSource=datasetTitles.Tables["titles"].DefaultView;
DataGrid1.DataBind();
}

. Auto Format
.

www.pupuol.com


: SQL-server

. DataView DataSet Sort

) ( Sort
.

SQL Order By

:
. Pubs title titles
:
private void Page_Load(object sender, System.EventArgs e)
{
SqlConnection sqlconnectionPubs = new
SqlConnection("server=(local);uid=sa;pwd=;database=pubs");
SqlDataAdapter sqldataadapterTitles =
new SqlDataAdapter("select title, notes,"+
"price from titles where type='business'", sqlconnectionPubs);
DataSet datasetTitles = new DataSet();
sqldataadapterTitles.Fill(datasetTitles, "titles");
DataView dataviewTitle =
datasetTitles.Tables["titles"].DefaultView;
dataviewTitle.Sort = "title";
DataGrid1.DataSource=dataviewTitle;
DataGrid1.DataBind();
}

www.pupuol.com

.
Stored Procedures .

www.pupuol.com


:
- .
:

strTableNameToBind

strSQL strConnectinString

bindToDataGrid

- SQL-Server .
:

strTableNameToAdd strConnectinString

InputsToAdd

addRecordsToSQLdb .

SQL Insert

.
Encapsulation !

www.pupuol.com

:
- ASP.NET

:
ADO.NET

:

SQL .
SQL

Cache .

ADO.NET .

www.pupuol.com


:
MyTestDB .
ID

.
.

: tblEntry

tblEntry .
: tblSell

tblSell .
Foreign key .

Relationship ) : (

www.pupuol.com

Relationship .
New ) ( .

www.pupuol.com

. Foreign key Relationship


. ( )

. Query Analyzer

Create Procedure rptDiff


As
select distinct myTestDB.dbo.tblEntry.ID ,myTestDB.dbo.tblEntry.Entry_No , myTestDB.dbo.tblSell.Sell_No,
(myTestDB.dbo.tblSell.Sell_No - myTestDB.dbo.tblEntry.Entry_No) as final_result
from myTestDB.dbo.tblEntry LEFT OUTER JOIN myTestDB.dbo.tblSell
ON (myTestDB.dbo.tblEntry.ID = myTestDB.dbo.tblSell.ID)
Return

www.pupuol.com


Enterprise

. manager

:
Exec rptDiff

.
SqlDataAdapter ADO.NET
:
private void Page_Load(object sender, System.EventArgs e)
{
SqlConnection sqlconnectionForum = new
SqlConnection("server=(local);uid=sa;pwd=;database=MyTestDB");
SqlDataAdapter sqldataadapterSP =
new SqlDataAdapter("rptDiff",sqlconnectionForum);
sqldataadapterSP.SelectCommand.CommandType =
CommandType.StoredProcedure ;
DataSet datasetSP = new DataSet();

www.pupuol.com


;) "sqldataadapterSP.Fill( datasetSP,"tblEntry
;DataGrid1.DataSource = datasetSP.Tables["tblEntry"].DefaultView
;)(DataGrid1.DataBind
}

:

. MyTestDB
ID :
:

Query Analyzer Enterprise manager .

MyTestDB Stored procedures


.

New Stored procedure . ) (


:

)Create Procedure rpt_ID_Diff(@Sell_ID int


As
select distinct (myTestDB.dbo.tblSell.Sell_No - myTestDB.dbo.tblEntry.Entry_No) as final_result
from myTestDB.dbo.tblEntry LEFT OUTER JOIN myTestDB.dbo.tblSell
ON (myTestDB.dbo.tblEntry.ID = myTestDB.dbo.tblSell.ID) where
myTestDB.dbo.tblSell.ID=@Sell_ID
Return
GO

www.pupuol.com

. Enterprise manager
: Query analyzer
exec rpt_ID_diff 2

:
private void Page_Load(object sender, System.EventArgs e)
{
SqlConnection
MyConnection = new
SqlConnection("server=(local);uid=sa;pwd=;database=MyTestDB");
//Calling the DisplayCustomers stored procedure
SqlDataAdapter MyCommand = new
SqlDataAdapter("rpt_ID_Diff", MyConnection);
MyCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
//Adding the SQL parameter
MyCommand.SelectCommand.Parameters.Add(
new SqlParameter("@Sell_ID",SqlDbType.Int ));
//Specifying the parameter value
MyCommand.SelectCommand.Parameters["@Sell_ID"].Value = 3;

www.pupuol.com

; )

;)(DataSet DS = new DataSet


;)"MyCommand.Fill(DS, "tblSell
// write & show final_result value
( Response.Write
"final_result = "+
)(DS.Tables["tblSell"].Rows[0][0].ToString
}

:
) (
.

SQL
. .

:
myTestDB.dbo.tblSell.ID
.
.

ExecuteScalar SqlCommand
.

)private void Page_Load(object sender, System.EventArgs e


{
SqlConnection MyConnection = new
;)"SqlConnection("server=(local);uid=sa;pwd=;database=MyTestDB

www.pupuol.com


SqlCommand newCmd = new
;)SqlCommand("select MAX(tblSell.ID) from tblSell",MyConnection
;)(MyConnection.Open
;)(int intRes = (int)newCmd.ExecuteScalar
;)(MyConnection.Close
; )Response.Write(intRes
}

: T-SQL


:
;"'" strSQL = " select * from tbl1 where field1='"+ text1.text +

Text1.text

:
:

myTestDB.dbo.tblEntry.ID .

) BorderSize=0 (

www.pupuol.com


RequiredFieldValidators

.
private void btnAdd_Click(object sender, System.EventArgs e)
{
SqlConnection sqlconnectionMyTestDB = new
SqlConnection("server=(local);uid=sa;pwd=;database=MyTestDB");
SqlDataAdapter sqldataadapterEntry = new
SqlDataAdapter("select * from tblEntry", sqlconnectionMyTestDB);
String insertCmd = "INSERT INTO tblEntry(id, Entry_no) VALUES( " +
"@Id, @Entry_No )";
SqlCommand sqlcommandEntry = new SqlCommand(insertCmd,
sqlconnectionMyTestDB);
sqlcommandEntry.Parameters.Add(
new SqlParameter("@Id", SqlDbType.Int));
sqlcommandEntry.Parameters["@Id"].Value = txtID.Text;
sqlcommandEntry.Parameters.Add(
new SqlParameter("@Entry_No", SqlDbType.Int));
sqlcommandEntry.Parameters["@Entry_No"].Value = txt_Entry_No.Text;

sqlcommandEntry.Connection.Open();
sqlcommandEntry.ExecuteNonQuery();
sqlcommandEntry.Connection.Close();
DataSet datasetEntry = new DataSet();
sqldataadapterEntry.Fill(datasetEntry, "tblEntry");

DataGrid1.DataSource=datasetEntry.Tables["tblEntry"].DefaultView;
DataGrid1.DataBind();
DataGrid1.Visible = true;
}

www.pupuol.com

: OLE DB
OLE DB ADO.NET

System.Data.OleDb . System.Data.OleDb.OleDbCommand

SQL Update Insert Select Delete


.

:
.
XP New
Blank DataBase
access_db.mdb . ) ( Create Table in

design View

SQL-Server . ) ( .

) ( tblEntry .
Primary key ) .(

www.pupuol.com

www.pupuol.com

- .

. Primary key

! )

.(... Primary key SQL-Server )


Primary key (.

Primary key ID .
.

ASP.NET )
. (

www.pupuol.com

.
:
using System.Data.OleDb;

: Add
private void btnAdd_Click(object sender, System.EventArgs e)
{
//g:\inetpub\wwwroot\classes\ch09\ex05\acess_db.mdb
// or :
//MapPath : Returns the physical file path that corresponds to
//the specified virtual path on the Web server.
String FilePath;
FilePath = Server.MapPath("acess_db.mdb");
// Connect to Database
OleDbConnection cnAccess = new
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;"+
"Data Source="+ FilePath );
cnAccess.Open();

//Make the insert statement


string sInsertSQL = "insert into tblEntry values(" +
txtID.Text + "," + txt_Entry_No.Text

www.pupuol.com

+ ")";


//Make the OleDbCommand object
OleDbCommand cmdInsert = new OleDbCommand(sInsertSQL,cnAccess);
// This not a query so we do not expect any return data so use
// the ExecuteNonQuery method
cmdInsert.ExecuteNonQuery();
// displaying data
OleDbDataAdapter sqldataadapterEntry =
new OleDbDataAdapter("select * from tblEntry",cnAccess);
DataSet datasetEntry = new DataSet();
sqldataadapterEntry.Fill(datasetEntry, "tblEntry");

DataGrid1.DataSource=datasetEntry.Tables["tblEntry"].DefaultView;
DataGrid1.DataBind();
DataGrid1.Visible = true;
}

mdb ASP

. Server.MapPath
. OleDb Sql

Recordset System.Data.OleDb.OleDbDataReader
. . ADO
:
. OleDbDataReader
: Label
using System.Data.OleDb ;
using System.Text; // for StringBuilder

www.pupuol.com

tblEntry
HTML

System.Text

+ )!( . StringBuilder

. string

private void Page_Load(object sender, System.EventArgs e)


{
String FilePath;
FilePath = Server.MapPath("acess_db.mdb");
// Connect to Database
OleDbConnection cnAccess = new
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;"+
"Data Source="+ FilePath );
cnAccess.Open();
//Make the select statement
string sSelectSQL = "select * from tblEntry";
//'Make the OleDbCommand object
OleDbCommand cmdSelect = new OleDbCommand(sSelectSQL,cnAccess);
//This query should return an OleDbDataReader so we use the
//ExecuteReader method
StringBuilder sbResults = new StringBuilder();
OleDbDataReader drEmp = cmdSelect.ExecuteReader();

drEmp.Read();
sbResults.Append ("<Table>");
do
{
sbResults.Append ("<TR><TD>");
sbResults.Append ( drEmp.GetInt32(0).ToString());
sbResults.Append ("</TD><TD>");
sbResults.Append ( drEmp.GetInt32(1).ToString() );
sbResults.Append ("</TD><TR>");
}while (drEmp.Read());
sbResults.Append ("</Table>");
lblResult.Text = sbResults.ToString();
}

www.pupuol.com

: OleDbDataAdapter
Data Adapter
.
:

: InsertCommand

: SelectCommad SQL

: DeleteCommand SQL .

System.Data.DataSet System.Data.DataTable
System.Data.DataRow : System.Data.DataColumn

DataSet .Net Framework .


ADO

Recordset . DataSet XML

. XML
Cross-Platform DataSet .

. DataTable DataRelation
. DataRow DataColumn
) .(

www.pupuol.com

:
DataTable .

Label :
; using System.Data.OleDb
using System.Text; // for StringBuilder

- . DataSet

www.pupuol.com


private void Page_Load(object sender, System.EventArgs e)
{
String FilePath;
FilePath = Server.MapPath("acess_db.mdb");
// Connect to Database
OleDbConnection cnAccess = new
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;"+
"Data Source="+ FilePath );
cnAccess.Open();
// Make the select statement
string sSelectSQL = "select * from tblEntry";
//Make the OleDbCommand object
OleDbCommand cmdSelect = new OleDbCommand(sSelectSQL,cnAccess);
OleDbDataAdapter daEmp = new OleDbDataAdapter(cmdSelect);
DataSet dsEmp = new DataSet();
StringBuilder sbResults = new StringBuilder();
// Fill the data with the output of the cmdSelect command. Note
// that the dataadapter is associated with the command. We use
// the dataadapter to fill the dataset.
daEmp.Fill(dsEmp, "tblEntry");
PrintRows(dsEmp);
}
private void PrintRows(DataSet myDataSet)
{
StringBuilder sbResult =new StringBuilder();
// Iterate through all the DataTables in the DataSet
foreach( DataTable dtEmp in myDataSet.Tables )
{
sbResult.Append("<Table>");
// Iterate through all the DataRows in the DataTable
foreach( DataRow drEmp in dtEmp.Rows )
{
sbResult.Append("<TR>");
// Iterate through all the DataColumns in the DataRow
foreach (DataColumn dcEmp in dtEmp.Columns)
{
sbResult.Append("<TD>");
sbResult.Append(drEmp[dcEmp]);
sbResult.Append("</TD>");
}
sbResult.Append("</TR>");
}
sbResult.Append("</Table>");
}
lblResult.Text = sbResult.ToString();
}

www.pupuol.com

- txtID Label
.

New Post - .

- tblEntry MyTestDB
Entry_No .

- tblArea
.

- tblPosts

www.pupuol.com

:
ASP.NET
.
.

:
Repeater .
Templates Header Footer
.

DataSource DataBind .

Templates . ItemTemplates
. AlternatingItemTemplate

www.pupuol.com


. HeaderTempalte

FooterTemplate .

SeperaterTemplate
.

:
Titles Pubs Title :
Repeater .

View HTML Source


Design HTML .

HeaderTemplate HTML

>"<asp:Repeater id="Repeater1" runat="server


><HeaderTemplate
>"<table border="1
><TR
><TD><B>Title table</B></TD
></TR
></HeaderTemplate

AlternatingTemplate Title :
><AlternatingItemTemplate
><tr
>"<td style="background-color: lightblue
><b
><%# DataBinder.Eval(Container.DataItem,"title") %
></b
></td
></tr
></AlternatingItemTemplate

www.pupuol.com


:
DataBinder.Eval

HTML XML ItemTemplate


.
<ItemTemplate>
<tr>
<td style="background-color: lightgray">
<%# DataBinder.Eval(Container.DataItem,"title") %>
</td>
</tr>
</ItemTemplate>

: FooterTemplate
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>

Design

: DataMember

private void Page_Load(object sender, System.EventArgs e)


{
SqlConnection cnn = new
SqlConnection("server=(local);uid=sa;pwd=;database=pubs" );
SqlDataAdapter dtAdap = new
SqlDataAdapter("select title from titles",cnn);
DataSet datasetTitles = new DataSet();
dtAdap.Fill(datasetTitles, "titles");
Repeater1.DataMember ="titles";
Repeater1.DataSource = datasetTitles.Tables["titles"].DefaultView;
Repeater1.DataBind();
}

www.pupuol.com

:
DataList .

repeater Template
. DataSource

DataBind . Templates
:

ItemTemplate, AlternatingTemplate, HeaderTemplate, FooterTemplate,


SeparatorTemplate
SelectedItemTemplate EditItemTemplate
.

:
.
Edit Templates Header and footer templates .

Templates

. Header Footer

. :

- Header and footer templates .

www.pupuol.com


Template .

ItemTemplates .
Edit Templates Item Templates

) .(

- ItemTemplates .
Label Item
Templates Drag ) .( .
lblNotes lblTitles .

DataBindings

Binable properties Text

Custom binding expresion


DataBinder.Eval ) .(

:
)"DataBinder.Eval(Container, "DataItem.Title

Notes :
)"DataBinder.Eval(Container, "DataItem.Notes

www.pupuol.com

- .
.
.

- .

www.pupuol.com

private void Page_Load(object sender, System.EventArgs e)


{
SqlConnection cnn = new
SqlConnection("server=(local);uid=sa;pwd=;database=pubs" );
SqlDataAdapter dtAdap = new
SqlDataAdapter("select title,notes from titles",cnn);
DataSet datasetTitles = new DataSet();
dtAdap.Fill(datasetTitles, "titles");
DataList1.DataSource = datasetTitles.Tables["titles"].DefaultView;
DataList1.DataBind();
}

: dropDownList
.

:
DropDownList Pubs Titles Title

. Label

. Label DropDownList
.

www.pupuol.com


private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack) // run 1 time
{
SqlConnection cnn = new
SqlConnection("server=(local);uid=sa;pwd=;database=pubs" );
SqlDataAdapter dtAdap = new
SqlDataAdapter("select title from titles",cnn);
DataSet datasetTitles = new DataSet();
dtAdap.Fill(datasetTitles, "titles");
DropDownList1.DataTextField ="title";
DropDownList1.DataSource = datasetTitles.Tables["titles"].DefaultView;
DropDownList1.DataBind();
}
}

DataTextField

AutoPostBack

. true DropDownList
. SelectedIndexChanged
.

private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)


{
Label1.Text = DropDownList1.SelectedItem.Text;
}

PostBack Page_Load
.
if (!Page.IsPostBack) // run 1 time

www.pupuol.com


TreeView ToolBar TabControl MultiPageControl

http://msdn.microsoft.com/downloads/samples/Internet/ASP_DOT_NET_ServerControls/WebControls/

:
aspx

:
Paging .

.
:

Property builder . Paging )



( Apply Ok :

www.pupuol.com

. Paging -

private void Page_Load(object sender, System.EventArgs e)


{
if(!Page.IsPostBack)
bindToDatGrid();
}
void bindToDatGrid()
{
SqlConnection cnn = new
SqlConnection("server=(local);uid=sa;pwd=;database=pubs" );
SqlDataAdapter dtAdap = new
SqlDataAdapter("select * from sales",cnn);
DataSet dsetSales = new DataSet();
dtAdap.Fill(dsetSales, "sales");
DataGrid1.DataSource = dsetSales.Tables["sales"].DefaultView;
DataGrid1.DataBind();
}

www.pupuol.com

. .

. PageIndexChanged .
. Paging

private void DataGrid1_PageIndexChanged(object source,


)System.Web.UI.WebControls.DataGridPageChangedEventArgs e
{
; DataGrid1.CurrentPageIndex = e.NewPageIndex
;)(bindToDatGrid
}

:
Sort .
.

)private void Page_Load(object sender, System.EventArgs e


{
)if(!Page.IsPostBack
;)"bindToDatGrid("qty
}
)void bindToDatGrid(string sort_field
{
SqlConnection cnn = new
;) "SqlConnection("server=(local);uid=sa;pwd=;database=pubs

www.pupuol.com


SqlDataAdapter dtAdap = new
;)SqlDataAdapter("select * from sales",cnn
;)(DataSet dsetSales = new DataSet
;)"dtAdap.Fill(dsetSales, "sales
= DataView dataviewSales
;dsetSales.Tables["sales"].DefaultView
;dataviewSales.Sort = sort_field

;DataGrid1.DataSource = dataviewSales
;)(DataGrid1.DataBind
}

Header

Property builder . General

Allow sorting .
.

SortCommand .

private void DataGrid1_SortCommand(object source,


)System.Web.UI.WebControls.DataGridSortCommandEventArgs e
{
;string SortField = (string)e.SortExpression
;)bindToDatGrid(SortField
}

www.pupuol.com


:
.
Edit Update
Edit

Update .
.
Property builder . Columns Edit, Update,
Cancel ) ( Apply Ok .

Northwind SQL-Server

.
)private void Page_Load(object sender, System.EventArgs e
{
)if(!Page.IsPostBack
;)(bindToDatGrid
}
)(void bindToDatGrid
{
SqlConnection cnn = new
;) ";=SqlConnection("DATABASE=Northwind;SERVER=localhost;UID=sa;PWD
SqlDataAdapter dtAdap = new
SqlDataAdapter("SELECT employeeid, titleofcourtesy,"+
;)" firstname, lastname, title, country FROM Employees",cnn
;)(DataSet dsetSales = new DataSet
;)"dtAdap.Fill(dsetSales, "sales
;DataGrid1.DataSource = dsetSales.Tables["sales"].DefaultView
;)(DataGrid1.DataBind
}

edit

EditCommand
:

www.pupuol.com

private void DataGrid1_EditCommand(object source,


System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
// Set the current item to edit mode
DataGrid1.EditItemIndex = e.Item.ItemIndex;
bindToDatGrid();
}

. Edit, Update, Cancel -


CancelCommand

www.pupuol.com

private void DataGrid1_CancelCommand(object source,


System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
// Reset the edit mode for the current item
DataGrid1.EditItemIndex = -1;
bindToDatGrid();
}

. Update
. UpdateCommand
.

private void DataGrid1_UpdateCommand(object source,


System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
string
string
string
string
string
string

employeeid = ((TextBox)e.Item.Cells[1].Controls[0]).Text;
titleofcourtesy = ((TextBox)e.Item.Cells[2].Controls[0]).Text;
firstname = ((TextBox)e.Item.Cells[3].Controls[0]).Text;
lastname = ((TextBox)e.Item.Cells[4].Controls[0]).Text;
title = ((TextBox)e.Item.Cells[5].Controls[0]).Text;
country = ((TextBox)e.Item.Cells[6].Controls[0]).Text;

SqlConnection conn = new


SqlConnection("DATABASE=Northwind;SERVER=localhost;UID=sa;PWD=;");
// Prepare the command text
String strCmd = "UPDATE Employees SET title='" +
title + "'," + "country='" + country + "'" +
" WHERE employeeid='" + employeeid + "'";
SqlCommand cmd = new SqlCommand(strCmd, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
// Reset the edit mode for the current item
DataGrid1.EditItemIndex = -1;
// create data source again.........
bindToDatGrid();
}

www.pupuol.com

:
.

General Property builder


! Ok Apply . Show footer

:
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
bindToDatGrid();
}
void bindToDatGrid()
{
SqlConnection cnn = new
SqlConnection("DATABASE=Northwind;SERVER=localhost;UID=sa;PWD=;" );
SqlDataAdapter dtAdap = new
SqlDataAdapter("SELECT * FROM [Order Details]",cnn);
DataSet dsetSales = new DataSet();
dtAdap.Fill(dsetSales, "[Order Details]");
DataGrid1.DataSource = dsetSales.Tables["[Order Details]"].DefaultView;
DataGrid1.DataBind();
}

OrderID, ProductID, UnitPrice, Northwind Order Details

. Footer . Quantity, Discount

www.pupuol.com


ItemDataBound

.
:

ItemDataBound

:
// calc total
private double[] runningTotal = new double[16] ;

:
private void CalcTotal(string _price, int i)
{
try
{
runningTotal[i] += Double.Parse(_price);
}
catch
{
//A value was null
}
}

:
private void DataGrid1_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
//is called as each row in the data source is bound to the DataGrid
if ( e.Item.ItemType == ListItemType.Item
|| e.Item.ItemType == ListItemType.AlternatingItem)
{
CalcTotal( e.Item.Cells[3].Text ,3);
CalcTotal( e.Item.Cells[4].Text ,4);
}
else if(e.Item.ItemType == ListItemType.Footer )
{
e.Item.Cells[2].Text="Total: ";
e.Item.Cells[3].Text = runningTotal[3].ToString();
e.Item.Cells[4].Text = runningTotal[4].ToString();
}
}

www.pupuol.com

:
- Delete .


) DeleteCommand (.

-
) (

Order Details


paging .

www.pupuol.com

Vous aimerez peut-être aussi