Professional Documents
Culture Documents
Giao Trinh Giao - Trinh - ASP - NETvoi - CShaASP - Netvoi CSharp
Giao Trinh Giao - Trinh - ASP - NETvoi - CShaASP - Netvoi CSharp
NET Framwork v c bn v C#
I. Gii thiu chung v ASPNetFramwork
Trong gio trnh ny chng ta s hc ASP.NET trn IDE VisualStdio2005(Bn c th s dng
Viusal Web Develop 2005 ).
to mt Wesite mi bn khi ng VS. giao din ca n s hin ra nh sau:
Hnh 1
Trong Box Recent Project bn chn Web site dng Create
Hp thoi New Website hin ra bn chn ASP.NET WebSite ri chn th mc bn
Website v ngn ng kch bn bn vit Web v nhn OK
http://www.ebook.edu.vn
Hnh 2
VS s to ra mt website vi tn ca Website l tn bn va t v mc nh s c mt
trang Default.aspx nh hnh sau:
Hnh 3
http://www.ebook.edu.vn
http://www.ebook.edu.vn
http://www.ebook.edu.vn
V d: Trang UnderstandEvent.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="UnderstandEvent.aspx.cs" Inherits="UnderstandEvent" %>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = TextBox1.Text;
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
http://www.ebook.edu.vn
</html>
Trong v d trn gm 3 iu khin ca ASP.NET l TextBox, Label, v Button, mi khi
ngi s dng nhp d liu vo Textbox v nhn vo Button s kin Button1_Click c a
ra v in d liu t TextBox v Label.
http://www.ebook.edu.vn
sau:
Trang Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
http://www.ebook.edu.vn
</div>
</form>
</body>
</html>
Trang Defautl.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
http://www.ebook.edu.vn
3. InitComplete
4. PreLoad
5. Load
6. LoadComplete
7. PreRender
8. PreRenderComplete
9. SaveStateComplete
10. Unload
S dng thuc tnh Page.IsPostBack
Vi s kin Load ca trang th khi ti trang ln th c mt s kin no c a ra,
nu c ngha mi ln load li trang n li thc hin cng vic , cn nu ta a thm vo
thuc tnh Page.IsPostBack th ta c th iu khin c s kin no c thc hin v s
kin no khng khi trang c ti li.
Kiu C#
Kiu .Net
S Byte
M t
byte
Byte
char
Char
Kiu k t Unicode
bool
Boolean
Gi tr true/false
sbyte
Sbyte
short
Int16
ushort
Int16
int
Int32
uint
Int32
float
Single
http://www.ebook.edu.vn
3,4E+38, vi 7 ch s c ngha.
Double
Double
Decimal
Decimal
2. khai bo bin
C php: Kiu Tn_bin;
V d:
string giatri_chuoi;
int giatri_nguyen;
ch bin c th bao gm cc ch ci, ch s(khng c ng u) v k t _ (ni)
bin trong C# phn bit ch hoa v ch thng.
3. S dng cc trnh by
a. trnh by if if else
Khi bn cn kim tra mt iu kin no trc khi thc hin cng vic, hoc kim tra
iu kin nu ng th lm vic cn khc th khng lm bn c th dng trnh by if if else
c php:
if(iu_kin)
{
//thc hin cng vic
}
if(iu_kin)
{
// thc hin cng vic 1
}
http://www.ebook.edu.vn
10
else
{
//thc hin cng vic 2
}
Lu bn c th dng nhiu cp if else lng nhau:
V d:
Vd1
if (conn.State != ConnectionState.Open)
conn.Open();
Vd2
if (1 > 2)
MessageBox.Show("1>2");
else
MessageBox.Show("2>1");
http://www.ebook.edu.vn
11
break;
default:
//thuc hien cong viec mac dinh
break;
}
http://www.ebook.edu.vn
12
do
{
MessageBox.Show(i.ToString());
i++;
} while (i < 3);\
http://www.ebook.edu.vn
13
}
}
4. Trang asp.net
Trang asp.net c ui m rng l .aspx v km theo mt lp phc v n ng
sau(Code behind).
http://www.ebook.edu.vn
14
vit code C# trong trang aspnet ta c th khai bo v s dng trc tip trong trang
asp.net, trong file code behind, hoc t mt thnh phn th vin v ta gi vo.
y l mt v d n gin
Trang basic.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Basic.aspx.cs"
Inherits="_Default" %>
http://www.ebook.edu.vn
15
</div>
</form>
</body>
</html>
4.2
V trang aspnet ca chng ta k tha t trang aspx.cs ln trong trang .aspx chng ta
mun gi d liu t bin hay hm trong file .aspx.cs chng ta phi khai bo vi b ng truy
cp protected hoc public.
V d sau:
Trang codebehind.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="codebehind.aspx.cs"
Inherits="codebehind" %>
http://www.ebook.edu.vn
16
</body>
</html>
Trang codebehind.aspx.cs
using System;
public partial class codebehind : System.Web.UI.Page
{
protected string _hello;
protected void Page_Load(object sender, EventArgs e)
{
_hello = "Hello World";
lblhello.Text = _hello;
}
}
Trong v d trn c s dng mt iu khin asp.net l Label cc bn s c hc trong
chng sau, chng ny bn hiu n l mt iu khin hin th d liu.
Bn thy trong phn code behind c khai bo mt bin _hello kiu string v b ng
truy cp l protected trong s kin Page_Load(khi trang c ti ln) chng ta gn _hello =
"Hello World"; v sau gn gi tr cho Label bng gi tr ca _hello. Cn trong trang .aspx
chng ta c s dng th <%= %> ly gi tr ca _hello in ra mn hnh.
4.3 to mt lp th vin
to mt lp th vin phc v cho trang asp.net bn c th to mt thnh phn th
vin ng DLL ri nhp tham chiu n n s dng(chng ta s hc n trong phn
asp.net nng cao). Trong ng dng web ASP.NET Framework c mt ASP.NET FOLDER l
App_Code cho php chng ta vit cc lp th vin y v c th s dng trong cc trang
ca ng dng web.
to th mc App_code bn lm theo cc bc sau y:
bc 1: nhn chut phi vo Solution v chn theo ng dn ca nh di y.
http://www.ebook.edu.vn
17
http://www.ebook.edu.vn
18
Add.
a, nh ngha lp:
Khai bo:
[Thuc tnh] [b sung truy cp] Class [Tn lp] : [Lp c s]
{
//cc bin, phng thc hay thuc tnh ca lp
}
V d: Lp HelloWorld.cs
class HelloWorld
{
public string SayMessage()
{
return "Hello World";
http://www.ebook.edu.vn
19
}
}
Trong v d trn phng thc SayMessage s v chui Hello World.
c, Hm v th tc
Bn c th hiu n gin hm phi c gi tr tr v cn th tc nh mt on m ch
thc hin khi c chng ta gi. th tc cn c gi l hm khng kiu, hm v th tc
trong C# gi chung l phng thc.
V d hm:
public static int Sum(int _a, int _b)
{
return _a + _b;
}
Trn l mt hm dng tnh tng ca hai s, nh bn thy tr v d liu cho hm
chng ta dng t kho return, b sung truy cp public c ngha hm c s dng trong
ton ng dng, t kho static y l mt phng thc tnh ln c th s dng m khng cn
phi khai bo khi to i tng
V d v th tc
public static void HelloProcedure(string _bien)
{
System.Web.HttpContext.Current.Response.Write(_bien);
}
S dng lp HellWorld trong trang aspx ca chng ta
Trang UseHelloworld.aspx
http://www.ebook.edu.vn
20
5. C bn v lp trong C#
5.1 Khai bo Field v thuc tnh
http://www.ebook.edu.vn
21
V d v Field
public class HelloWorld
{
public string _Message;
public string SayMessage()
{
return _Message;
}
}
Trong on m trn bn thy Field _Message c khai bo kiu string v b ng truy
cp l public, v _Message c tr v gi tr bi phng thc SayMessage().
V d v thuc tnh
public class HelloWorld
{
public string _Message;
public string Message
{
get { return _Message; }
set { _Message = value; }
}
}
Mt thuc tnh Message c khai bo trn gm 2 phng thc get tr v gi tr cho
Message v phng thc set thit lp gi tr cho Message. Thuc tnh Message trn l
phng thc va c va ghi. nu bn xy dng thuc tnh ch c th bn ch cung cp
phng thc get hay thuc tnh ch ghi bn cung cp cho thuc tnh phng thc set.
http://www.ebook.edu.vn
22
http://www.ebook.edu.vn
23
<head runat="server">
<title>S dng phng thc khi dng ca lp</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblhello" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
Trang UseConstruction.aspx.cs
using System;
public partial class UseConstruction : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Construction construc = new Construction(5, 6);
lblhello.Text = "Gi tr l: " + construc.Sum().ToString();
}
}
http://www.ebook.edu.vn
24
V d:
Bn to mt lp
Lp UseOverload.cs
using System;
public class UseOverload
{
public static int Sum(int a, int b)
{
return a + b;
}
public static int Sum(int a, int b, int c)
{
return a + b + c;
}
public static int Sum(int a, int b, int c, int d)
{
return a + b + c + d;
}
}
Trong lp ny gm 3 hm tnh tng ln lt c a vo 2,3,4 i s
S dng lp ny trong trang ASP.NET
Trang Overloading.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Overloading.aspx.cs"
Inherits="Overloading" %>
http://www.ebook.edu.vn
25
http://www.ebook.edu.vn
26
}
Trong lp ny bn gi ln lt cc phng thc tnh tng vi 2,3,4 i s truyn gi
tr vo cc Label tng ng cng tn.
Kt xut ca chng trnh:
http://www.ebook.edu.vn
27
{
public static int Sum(int a, int b)
{
return a + b;
}
}
}
V lp Pheptru.cs
using System;
namespace iTechPro.Tinhtoan
{
public class Pheptru
{
public static int Minus(int a, int b)
{
return a - b;
}
}
}
Nh bn thy hai lp ny nm trong Namespaces iTechPro.Tinhtoan, th iTechPro l
Namespaces ln nht, cn Namespaces Tinhtoan l con ca iTechPro v trong tnh ton cha
cc lp Phepcong v Pheptru.
S dng Namespaces ny trong trang asp.net
Trang Namespaces.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Namespaces.aspx.cs"
Inherits="Namespaces" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
http://www.ebook.edu.vn
28
http://www.ebook.edu.vn
29
5.5 Lp Partial
.Net cho php chng ta to ra mt lp trong nhiu file khc nhau mi File cung cp hay
x l mt cng vic g trn lp .
V d sau y chng ta s to mt lp Calculator vi 2 phng thc cng v tr nm
trn hai File khc nhau.
File Calminus.cs
using System;
namespace iTechPro.Tinhtoan
{
public partial class Calculator
{
public static int Minus(int a, int b)
{
return a - b;
}
}
}
File Calsum.cs
using System;
namespace iTechPro.Tinhtoan
http://www.ebook.edu.vn
30
{
public partial class Calculator
{
public static int Sum(int a, int b)
{
return a + b;
}
}
}
Nh cc bn thy hai file Calsum v Calminus cha ng cng mt tn lp Calculator
v trong mi File cha ng mt phng thc ring l thnh phn ca lp .
S dng lp ny hon ton ging vi vic s dng mt lp khc.
File UsePartial.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UsePartial.aspx.cs"
Inherits="UsePartial" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>S dng lp Partial</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Lp Partial</h1>
Kt qu cng:
<asp:Label ID="lblcong" runat="server" Text="Label"></asp:Label><br
/><br />
Kt qu tr:
<asp:Label ID="lbltru" runat="server" Text="Label"></asp:Label>
http://www.ebook.edu.vn
31
</div>
</form>
</body>
</html>
V File UsePartial.aspx.cs
using System;
using iTechPro.Tinhtoan;
public partial class UsePartial : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblcong.Text = Calculator.Sum(5, 5).ToString();
lbltru.Text = Calculator.Minus(5, 5).ToString();
}
}
http://www.ebook.edu.vn
32
{
get { return _price; }
set { _price = value; }
}
}
public class ComputerProduct : BaseProduct
{
string _processor;
public string Processor
{
get { return _processor; }
set { _processor = value; }
}
}
public class TelevisionProduct : BaseProduct
{
bool _isDHTV;
public bool isDHTV
{
get { return _isDHTV; }
set { _isDHTV = value; }
}
}
Trong v d trn bn thy hai lp ComputerProduct v TelevisionProduct c k tha
t lp BaseProduct, trong lp BaseProduct c thuc tnh Price ln hai lp k tha s c k
tha thuc tnh ny.
Khi k tha t mt lp khc, bn c th overload cc thuc tnh v phng thc trong
lp ny. Overloading mt thuc tnh hay phng thc l mt tin ch khi bn mun thay i
cc ng x ca phng thc hay thuc tnh trong lp ny.
http://www.ebook.edu.vn
33
Overload mt phng thc hay thuc tnh t lp c s, th thuc tnh hay phng
thc ny phi c nh du vi t kho vitual hay abstract ca C# hay trong VB.NET l
Overridable hoc MustOverride.
V d, chng ta s a ra hai lp ProductBase v OnSaleProduct c k tha t lp
ProductBase nhng n s overload mt thuc tnh t lp ProductBase.
V d:
using System;
public class ProductBase
{
decimal _price;
public virtual decimal Price
{
get { return _price; }
set { _price = value; }
}
}
public class OnSaleProduct : ProductBase
{
public override decimal Price
{
get{ return base.Price / 2;}
set{base.Price = value;}
}
}
http://www.ebook.edu.vn
34
http://www.ebook.edu.vn
35
decimal Price
{
get;
}
void SaveProduct();
}
public class MusicProduct : IProduct
{
public decimal Price
{
get { return 20.99m; }
}
public void SaveProduct()
{
//Save Music Product
}
}
public class BookProduct : IProduct
{
public decimal Price
{
get { return 23.99m; }
}
public void SaveProduct()
{
//Save Book Product
}
}
http://www.ebook.edu.vn
36
Tn thuc tinh
nh hng
BackColor
BorderColor
BorderStyle
cssClass
Font
ForeColor
Style
ToolTip
ID
Tn ca iu khin
Tuy iu khin Label cha ng rt nhiu thuc tnh kt xut hin th nhng vi
kinh nghim ca mnh trong qu trnh thit k Web ti khuyn bn ln s dng thuc tnh
cssClass s dng mt lp css.
V d:
Gn thuc tnh trc tip
<asp:Label ID="Label1" BackColor="ActiveBorder"
BorderColor="ActiveCaption"
ForeColor="Blue" Font-Size="12pt" runat="server" Text="Trung tm cng
ngh cao iTechPro" />
S dng cssClass
<asp:Label ID="Label2" CssClass="label"
http://www.ebook.edu.vn
37
2, iu khin Literal
Ging vi iu khin Label bn c th dng Literal trnh by Text hoc ni dung
Html. Literal h tr mt thuc tnh m Label khng h tr l: thuc tnh Mode gm 3 gi
tr l: Pass through, Endcode, transform.
V d
<asp:Literal ID="lit1" runat="server" Text="<hr/>" Mode="PassThrough" />
<asp:Literal ID="lit2" runat="server" Text="<hr/>" Mode="Encode" />
<asp:Literal ID="lit3" runat="server" Text="<hr/>" Mode="Transform" />
Hin th:
http://www.ebook.edu.vn
38
Textmode
AccessKey
AutoCompleteType
AutoPostBack
Columms
Enabled
Cho php hay khng cho php nhp liu trn TextBox
MaxLength
ReadOnly
Rows
TabIndex
Wrap
AutoPostBack
http://www.ebook.edu.vn
39
Enabled
TabIndex
Text
TextAlign
Enables you to align the label for the check box. Possible values
are
Left and Right.
AutoPostBack
Checked
Enabled
GroupName
http://www.ebook.edu.vn
40
TabIndex
Text
TextAlign
AccessKey
CommandArgument
CommandName
Enabled
OnClientClick
PostBackUrl
TabIndex
Ch nh th t tab ca Button.
Text
UseSubmitBehavior
http://www.ebook.edu.vn
41
Thuc tnh
ImageUrl
Ch n ng dn ca nh
ImageAlign
V d.
<%@ Page Language="C#"%>
<script runat=server>
protected void btnDelete_Click(object sender, EventArgs e)
{
lblResult.Text = All pages deleted!;
http://www.ebook.edu.vn
42
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iTechPro</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" OnClick="Button1_Click" OnClientClick="return
confirm('Bn c chc chn?');" runat="server" Text="Button" /><br />
<asp:Label ID="Label1" runat="server" Text="iTechPro" />
</div>
</form>
</body>
</html>
Gii thch v d: trn on m trn trong form gm 2 iu khin Button v Label. Trong
iu khin Button ta gn vo 2 s kin: OnClientClick pha Clien, v OnClick pha Server
OnClientClick s thc hin khi ngi dng pha Client nhn vo Button, trong m Client
trnh by mt hm confirm trong javascript vi mc nh hi ngi dng xc nhn vic thc
hin no Bn c chc chn? nu ngi dng chn OK th S kin th 2 OnClick s c
thc hin cn nu chn Cancel th s kin pha Server khng c thc hin.
5. Thc hin chuyn trang
Mc nh khi bn nhn vo Button n s thc hin cng vic ngay trn trang v trang
ca chng ta s Load li mt ln nhng bn c th s dng thuc tnh PostBackUrl chuyn
sang mt trang khc.
V d bn c mt trang ButtonSearch.aspx
<%@ Page Language="C#" %>
http://www.ebook.edu.vn
43
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iTechPro</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblSearch" runat="server" Text="Search:" />
<asp:TextBox ID="txtSearch" runat="server" />
<asp:Button ID="btnSearch" Text="GO!" runat="server"
PostBackUrl="ButtonSearchResult.aspx" />
</div>
</form>
</body>
</html>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox txtSearch =
(TextBox)PreviousPage.FindControl("txtSearch");
http://www.ebook.edu.vn
44
lblSearch.Text = txtSearch.Text;
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iTechPro</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblSearch" runat="server" />
</div>
</form>
</body>
</html>
6. Ch nh mt Button mc nh.
V d trn trang ca bn c nhiu iu khin Button, khi nhp d liu bn li quen nhp
xong d liu v nhn nt Enter trn bn phm, bn c th mc nh nt cp nht d liu
lm mc nh khi nhn phm Emter. Nh v d di y.
<script runat="server">
void btnXacnhan_Click(object sender,EventArgs e)
http://www.ebook.edu.vn
45
{
lblThongbao.Text = txtHoten.Text;
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iTechPro</title>
</head>
<body>
<form id="form1" runat="server" defaultbutton="btnXacnhan">
<div>
<asp:Label ID="lblHoten" runat="server" Text="Nhp h tn" />
<asp:TextBox ID="txtHoten" runat="server" />
<hr />
<asp:Button ID="btnXacnhan" OnClick="btnXacnhan_Click" runat="server"
Text="Xc nhn" />
<asp:Button ID="btnBoqua" runat="server" Text="B qua" />
<hr />
<asp:Label ID="lblThongbao" runat="server" Text="" />
</div>
</form>
</body>
</html>
http://www.ebook.edu.vn
46
S khc nhau gia Command Event v Command Click l trong Command Event bn c
th cung cp Command Name v Command argument
Trong cc v d trc ti ly v d v s kin Command Click nn by gi ti s ly
mt v d v Command Event bn so snh.
V d trn trang bn c 3 iu khin Button nh v d di y:
<%@ Page Language="C#"%>
<script runat="server">
void hcubiuChon(object sender, CommandEventArgs e)
{
if (e.CommandName == "language")
{
switch (e.CommandArgument.ToString())
{
case "C#":
lblComandEvent.Text = "CShap";
break;
case "VBNET":
lblComandEvent.Text = "VB.NET";
break;
case "JAVA":
lblComandEvent.Text = "Java";
break;
}
}
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
http://www.ebook.edu.vn
47
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iTechPro</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Bn chn ngn ng:
<asp:Label ID="lblComandEvent" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="btna" OnCommand="hcubiuChon" CommandName="language"
CommandArgument="C#" runat="server" Text="C#" />
<asp:Button ID="btnb" OnCommand="hcubiuChon" CommandName="language"
CommandArgument="VBNET" runat="server" Text="VB.NET" />
<asp:Button ID="btnc" OnCommand="hcubiuChon" CommandName="language"
CommandArgument="JAVA" runat="server" Text="Java" />
</div>
</form>
</body>
</html>
http://www.ebook.edu.vn
48
AlternateText
DescriptionUrl
ImageAlign
ImageUrl
ng dn ca nh trn iu khin
V d
<%@ Page Language="C#" %>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
Random rnd = new Random();
switch (rnd.Next(3))
{
case 0:
Image1.ImageUrl = "Images/images1.jpg";
Image1.AlternateText = "Picture 1";
break;
case 1:
Image1.ImageUrl = "Images/images2.jpg";
Image1.AlternateText = "Picture 2";
break;
case 2:
Image1.ImageUrl = "Images/images3.jpg";
Image1.AlternateText = "Picture 3";
break;
http://www.ebook.edu.vn
49
}
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iTechPro</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="Image1" runat="server" />
</div>
</form>
</body>
</html>
2. iu khin ImageMap
Cho php bn to bn nh trn 1 nh hin th trn trang web m ngi dng pha
Client c th chn vo mt vng ca nh thc hin mt cng vic no .
V d
<%@ Page Language="C#"%>
<script runat="server">
void ImageMap1_Click(object sender, ImageMapEventArgs e)
{
http://www.ebook.edu.vn
50
switch (e.PostBackValue)
{
case "top":
lblResult.Text = "Day la phan dau";
break;
case "middle":
lblResult.Text = "day la phan giua";
break;
case "under":
lblResult.Text = "day la phan cuoi";
break;
}
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iTechPro</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ImageMap ID="ImageMap1" HotSpotMode="PostBack"
OnClick="ImageMap1_Click" ImageUrl="~/Images/jiwoo18034.jpg" runat="server">
<asp:RectangleHotSpot
PostBackValue="top"
Left="0"
http://www.ebook.edu.vn
51
Top="0"
Right="300"
Bottom="150"
AlternateText="Top" />
<asp:RectangleHotSpot
PostBackValue="middle"
Left="0"
Top="150"
Right="300"
Bottom="300"
AlternateText="middle" />
<asp:RectangleHotSpot
PostBackValue="under"
Left="0"
Top="300"
Right="300"
Bottom="450"
AlternateText="Under" />
</asp:ImageMap>
<asp:Label ID="lblResult" runat="server" />
</div>
</form>
</body>
</html>
Cc thuc tnh ca ImageMap ging vi Image v thm vo hai thuc tnh l:
- HotSpots: cho php bn in tp hp thng tin ca HotSpots c cha ng trong
iu khin ImageMap.
http://www.ebook.edu.vn
52
V. iu khin Panel
Khi bn cn a cc iu khin trang vo mt nhm gii thch ngha cho nhm
hoc c th l n hoc hin nhm iu khi nhn 1 s kin no trn trang ca bn, bn
c th dng iu khin panel.
Mt s thuc tnh ca iu khin panel m bn cn lu l:
- DefaultButton: Cho php bn nh ngha mt button mc nh trong panel m button
mc nh ny s c thc hin khi bn nhn phm Enter
- Direction: Cho php bn gn hoc thit t hng hin th ni dung c a ra trong
panel, c th l cc gi tr:NotSet, LeftToRight, and RightToLeft.
- GroupingText: Cho php bn trnh by Panel nh 1 Fieldset vi mt ch gii ring bit
- HorizontalAlign: Cho php bn ch ra hng ngang th hin ni dung ca panel v n
c th l cc gi tr: Center, Justify, Left, NotSet, and Right.
- ScrollBars: Cho php bn hin th scrollbars khi bn c nh chiu cao hoc chiu rng
ca panel v ni dung trong panel vt qu rng hoc cao , n c th l cc gi tr:
Auto, Both, Horizontal, None, and Vertical.
V d
<%@ Page Language="C#" %>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
for (int i = 1; i < 100; i++)
{
buletnghenghiep.Items.Add("Ngh "+i.ToString());
}
}
http://www.ebook.edu.vn
53
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iTechPro</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="panelpage" runat="server" GroupingText="iTechPro">
<table>
http://www.ebook.edu.vn
54
<tr>
<td>
<asp:Panel ScrollBars="auto" ID="panelsothich" Width="200px"
Height="200px" runat="server" GroupingText="S thch">
<asp:CheckBox ID="CheckBox1" Text="Bng " runat="server" /><br
/>
<asp:CheckBox ID="CheckBox2" Text="Xem phim" runat="server" /><br
/>
<asp:CheckBox ID="CheckBox3" Text="Kinh doanh" runat="server" />
</asp:Panel>
</td>
<td>
<asp:Panel ID="panelnghenghiep" Width="200px" Height="200px"
ScrollBars="Vertical" runat="server" GroupingText="Ngh nghip">
<asp:BulletedList ID="buletnghenghiep" runat="server">
</asp:BulletedList>
</asp:Panel>
</td>
</tr>
<tr>
<td>
<asp:CheckBox Checked="true" ID="chkhtsothich"
AutoPostBack="true" OnCheckedChanged="hcubiuSothich" Text="Hin th s thch"
runat="server" /><br />
<asp:CheckBox Checked="true" ID="chkhtnghenghiep"
AutoPostBack="true" OnCheckedChanged="hcubiuNghenghiep" Text="Hin th ngh
nghip" runat="server" /><br />
</td>
</tr>
</table>
</asp:Panel>
</div>
http://www.ebook.edu.vn
55
</form>
</body>
</html>
Tn thuc tinh
nh hng
BackColor
BorderColor
BorderStyle
cssClass
Font
ForeColor
Style
ToolTip
ID
Tn ca iu khin
http://www.ebook.edu.vn
56
Tuy iu khin Label cha ng rt nhiu thuc tnh kt xut hin th nhng vi
kinh nghim ca mnh trong qu trnh thit k Web ti khuyn bn ln s dng thuc tnh
cssClass s dng mt lp css.
V d:
Gn thuc tnh trc tip
<asp:Label ID="Label1" BackColor="ActiveBorder"
BorderColor="ActiveCaption"
ForeColor="Blue" Font-Size="12pt" runat="server" Text="Trung tm cng
ngh cao iTechPro" />
S dng cssClass
<asp:Label ID="Label2" CssClass="label"
runat="server" Text="Trung tm cng ngh cao iTechPro" />
Kt qu
2, iu khin Literal
Ging vi iu khin Label bn c th dng Literal trnh by Text hoc ni dung
Html. Literal h tr mt thuc tnh m Label khng h tr l: thuc tnh Mode gm 3 gi
tr l: Pass through, Endcode, transform.
V d
<asp:Literal ID="lit1" runat="server" Text="<hr/>" Mode="PassThrough" />
<asp:Literal ID="lit2" runat="server" Text="<hr/>" Mode="Encode" />
<asp:Literal ID="lit3" runat="server" Text="<hr/>" Mode="Transform" />
http://www.ebook.edu.vn
57
Hin th:
AccessKey
AutoCompleteType
AutoPostBack
Columms
Enabled
Cho php hay khng cho php nhp liu trn TextBox
MaxLength
ReadOnly
Rows
TabIndex
Wrap
http://www.ebook.edu.vn
58
AutoPostBack
Checked
Enabled
TabIndex
Text
TextAlign
Enables you to align the label for the check box. Possible values
are
Left and Right.
http://www.ebook.edu.vn
59
AccessKey
AutoPostBack
Checked
Enabled
GroupName
TabIndex
Text
TextAlign
AccessKey
CommandArgument
CommandName
Enabled
OnClientClick
PostBackUrl
http://www.ebook.edu.vn
60
TabIndex
Ch nh th t tab ca Button.
Text
UseSubmitBehavior
Thuc tnh
ImageUrl
Ch n ng dn ca nh
ImageAlign
V d.
<%@ Page Language="C#"%>
http://www.ebook.edu.vn
61
<script runat=server>
protected void btnDelete_Click(object sender, EventArgs e)
{
lblResult.Text = All pages deleted!;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iTechPro</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" OnClick="Button1_Click" OnClientClick="return
confirm('Bn c chc chn?');" runat="server" Text="Button" /><br />
<asp:Label ID="Label1" runat="server" Text="iTechPro" />
</div>
</form>
</body>
</html>
Gii thch v d: trn on m trn trong form gm 2 iu khin Button v Label. Trong
iu khin Button ta gn vo 2 s kin: OnClientClick pha Clien, v OnClick pha Server
OnClientClick s thc hin khi ngi dng pha Client nhn vo Button, trong m Client
trnh by mt hm confirm trong javascript vi mc nh hi ngi dng xc nhn vic thc
hin no Bn c chc chn? nu ngi dng chn OK th S kin th 2 OnClick s c
thc hin cn nu chn Cancel th s kin pha Server khng c thc hin.
http://www.ebook.edu.vn
62
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iTechPro</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblSearch" runat="server" Text="Search:" />
<asp:TextBox ID="txtSearch" runat="server" />
<asp:Button ID="btnSearch" Text="GO!" runat="server"
PostBackUrl="ButtonSearchResult.aspx" />
</div>
</form>
</body>
</html>
http://www.ebook.edu.vn
63
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox txtSearch =
(TextBox)PreviousPage.FindControl("txtSearch");
lblSearch.Text = txtSearch.Text;
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iTechPro</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblSearch" runat="server" />
</div>
</form>
</body>
</html>
6. Ch nh mt Button mc nh.
http://www.ebook.edu.vn
64
V d trn trang ca bn c nhiu iu khin Button, khi nhp d liu bn li quen nhp
xong d liu v nhn nt Enter trn bn phm, bn c th mc nh nt cp nht d liu
lm mc nh khi nhn phm Emter. Nh v d di y.
<script runat="server">
void btnXacnhan_Click(object sender,EventArgs e)
{
lblThongbao.Text = txtHoten.Text;
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iTechPro</title>
</head>
<body>
<form id="form1" runat="server" defaultbutton="btnXacnhan">
<div>
<asp:Label ID="lblHoten" runat="server" Text="Nhp h tn" />
<asp:TextBox ID="txtHoten" runat="server" />
<hr />
<asp:Button ID="btnXacnhan" OnClick="btnXacnhan_Click" runat="server"
Text="Xc nhn" />
<asp:Button ID="btnBoqua" runat="server" Text="B qua" />
<hr />
<asp:Label ID="lblThongbao" runat="server" Text="" />
http://www.ebook.edu.vn
65
</div>
</form>
</body>
</html>
<script runat="server">
void hcubiuChon(object sender, CommandEventArgs e)
{
if (e.CommandName == "language")
{
switch (e.CommandArgument.ToString())
{
case "C#":
lblComandEvent.Text = "CShap";
break;
case "VBNET":
lblComandEvent.Text = "VB.NET";
break;
case "JAVA":
lblComandEvent.Text = "Java";
http://www.ebook.edu.vn
66
break;
}
}
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iTechPro</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Bn chn ngn ng:
<asp:Label ID="lblComandEvent" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="btna" OnCommand="hcubiuChon" CommandName="language"
CommandArgument="C#" runat="server" Text="C#" />
<asp:Button ID="btnb" OnCommand="hcubiuChon" CommandName="language"
CommandArgument="VBNET" runat="server" Text="VB.NET" />
<asp:Button ID="btnc" OnCommand="hcubiuChon" CommandName="language"
CommandArgument="JAVA" runat="server" Text="Java" />
</div>
</form>
</body>
</html>
http://www.ebook.edu.vn
67
DescriptionUrl
ImageAlign
ImageUrl
ng dn ca nh trn iu khin
V d
<%@ Page Language="C#" %>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
Random rnd = new Random();
switch (rnd.Next(3))
{
case 0:
Image1.ImageUrl = "Images/images1.jpg";
Image1.AlternateText = "Picture 1";
break;
case 1:
Image1.ImageUrl = "Images/images2.jpg";
http://www.ebook.edu.vn
68
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iTechPro</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="Image1" runat="server" />
</div>
</form>
</body>
</html>
2. iu khin ImageMap
Cho php bn to bn nh trn 1 nh hin th trn trang web m ngi dng pha
Client c th chn vo mt vng ca nh thc hin mt cng vic no .
V d
http://www.ebook.edu.vn
69
<script runat="server">
void ImageMap1_Click(object sender, ImageMapEventArgs e)
{
switch (e.PostBackValue)
{
case "top":
lblResult.Text = "Day la phan dau";
break;
case "middle":
lblResult.Text = "day la phan giua";
break;
case "under":
lblResult.Text = "day la phan cuoi";
break;
}
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iTechPro</title>
</head>
<body>
<form id="form1" runat="server">
http://www.ebook.edu.vn
70
<div>
<asp:ImageMap ID="ImageMap1" HotSpotMode="PostBack"
OnClick="ImageMap1_Click" ImageUrl="~/Images/jiwoo18034.jpg" runat="server">
<asp:RectangleHotSpot
PostBackValue="top"
Left="0"
Top="0"
Right="300"
Bottom="150"
AlternateText="Top" />
<asp:RectangleHotSpot
PostBackValue="middle"
Left="0"
Top="150"
Right="300"
Bottom="300"
AlternateText="middle" />
<asp:RectangleHotSpot
PostBackValue="under"
Left="0"
Top="300"
Right="300"
Bottom="450"
AlternateText="Under" />
</asp:ImageMap>
<asp:Label ID="lblResult" runat="server" />
</div>
</form>
http://www.ebook.edu.vn
71
</body>
</html>
Cc thuc tnh ca ImageMap ging vi Image v thm vo hai thuc tnh l:
- HotSpots: cho php bn in tp hp thng tin ca HotSpots c cha ng trong
iu khin ImageMap.
- HotSpotMode:Cho php bn ch nh Enables you to specifythe behavior of the image
map when you click a region. Possible values are Inactive, Navigate, NotSet, and PostBack.
V. iu khin Panel
Khi bn cn a cc iu khin trang vo mt nhm gii thch ngha cho nhm
hoc c th l n hoc hin nhm iu khi nhn 1 s kin no trn trang ca bn, bn
c th dng iu khin panel.
Mt s thuc tnh ca iu khin panel m bn cn lu l:
- DefaultButton: Cho php bn nh ngha mt button mc nh trong panel m button
mc nh ny s c thc hin khi bn nhn phm Enter
- Direction: Cho php bn gn hoc thit t hng hin th ni dung c a ra trong
panel, c th l cc gi tr:NotSet, LeftToRight, and RightToLeft.
- GroupingText: Cho php bn trnh by Panel nh 1 Fieldset vi mt ch gii ring bit
- HorizontalAlign: Cho php bn ch ra hng ngang th hin ni dung ca panel v n
c th l cc gi tr: Center, Justify, Left, NotSet, and Right.
- ScrollBars: Cho php bn hin th scrollbars khi bn c nh chiu cao hoc chiu rng
ca panel v ni dung trong panel vt qu rng hoc cao , n c th l cc gi tr:
Auto, Both, Horizontal, None, and Vertical.
V d
<%@ Page Language="C#" %>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
for (int i = 1; i < 100; i++)
http://www.ebook.edu.vn
72
{
buletnghenghiep.Items.Add("Ngh "+i.ToString());
}
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>iTechPro</title>
</head>
http://www.ebook.edu.vn
73
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="panelpage" runat="server" GroupingText="iTechPro">
<table>
<tr>
<td>
<asp:Panel ScrollBars="auto" ID="panelsothich" Width="200px"
Height="200px" runat="server" GroupingText="S thch">
<asp:CheckBox ID="CheckBox1" Text="Bng " runat="server" /><br
/>
<asp:CheckBox ID="CheckBox2" Text="Xem phim" runat="server" /><br
/>
<asp:CheckBox ID="CheckBox3" Text="Kinh doanh" runat="server" />
</asp:Panel>
</td>
<td>
<asp:Panel ID="panelnghenghiep" Width="200px" Height="200px"
ScrollBars="Vertical" runat="server" GroupingText="Ngh nghip">
<asp:BulletedList ID="buletnghenghiep" runat="server">
</asp:BulletedList>
</asp:Panel>
</td>
</tr>
<tr>
<td>
<asp:CheckBox Checked="true" ID="chkhtsothich"
AutoPostBack="true" OnCheckedChanged="hcubiuSothich" Text="Hin th s thch"
runat="server" /><br />
<asp:CheckBox Checked="true" ID="chkhtnghenghiep"
AutoPostBack="true" OnCheckedChanged="hcubiuNghenghiep" Text="Hin th ngh
nghip" runat="server" /><br />
http://www.ebook.edu.vn
74
</td>
</tr>
</table>
</asp:Panel>
</div>
</form>
</body>
</html>
http://www.ebook.edu.vn
75
I. RequiredFieldValidator
2. Cch s dng:
a iu khin RequiredFieldValidator t ToolBox(trong phn Validation) vo trong Form
v thm vo cho n 2 thuc tnh
ControlToValidate: ch n iu khin s c kim tra
Text(hoc ErrorMessage): Thng bo li khi kim tra
3. V d
Code 1: Trang RequiredValidator.aspx
<%@ Page Language="C#" %>
<script runat="server">
void btnAccept_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
this.lblResult.Text = txtHoten.Text;
this.txtHoten.Text = "";
}
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Validator</title>
http://www.ebook.edu.vn
76
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblHoten" runat="server" Text="Nhp vo h tn" />
<asp:TextBox ID="txtHoten" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldtxtHoten"
ControlToValidate="txtHoten" runat="server" Text="* Bn phi nhp h
tn"></asp:RequiredFieldValidator><br />
<asp:Button ID="btnAccept" OnClick="btnAccept_Click" runat="server"
Text="Accept" /><br />
<asp:Label ID="lblResult" runat="server" Text="" />
</div>
</form>
</body>
</html>
1. ngha
Bn c th s dng CompareValidator Kim tra gi tr nhp vo c nm trong mt
khong nh nht v ln nht nh trc hay khng.
2. Cch s dng
Bn a iu khin CompareValidator t hp ToolBox vo Form v thit lp cho n mt
s thuc tnh sau:
3. V d
http://www.ebook.edu.vn
77
<script runat="server">
void btnAccept_Click(object sender,EventArgs e)
{
if (Page.IsValid)
{
this.lblThongbao.Text = txtDiem.Text;
}
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>RangeValidator</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Vo im</td>
<td><asp:TextBox ID="txtDiem" runat="server"></asp:TextBox></td>
<td>
http://www.ebook.edu.vn
78
<asp:RequiredFieldValidator ID="RequiredFieldDiem"
ControlToValidate="txtDiem" runat="server" ErrorMessage="Bn phi nhp
im"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeDiem" runat="server"
ControlToValidate="txtDiem" Type="Integer" MinimumValue="0" MaximumValue="10"
ErrorMessage="im phi nm trong khong t 0 n 10"></asp:RangeValidator>
</td>
</tr>
<tr>
<td colspan="3">
<asp:Button ID="btnAccept" OnClick="btnAccept_Click" runat="server"
Text="Thc hin" />
</td>
</tr>
<tr>
<td colspan="3">
<hr />
<asp:Label ID="lblThongbao" runat="server" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Trong v d trn ta dng hai i tng Validator cng kim tra gi tr nhp trn iu
khin txtDiem, iu khin RequiredFieldDiem dng kim tra v yu cu nhp gi tr cho
txtDiem cn iu khin RangeDiem yu cu nhp gi tr trong txtDiem phi nm trong
khong t 0 n 10.
http://www.ebook.edu.vn
79
1. ngha
iu khin RegularExpressionValidator cho php bn so snh gi tr nhp ti 1 trng
no trn Form vi mt quy tc nh trc. bn c th s dng cc biu thc quy tc
a ra cc chui mu nh l email addresses, Social Security numbers, phone numbers,
dates, currency, amounts, and product codes.
2. Cch s dng
Bn a iu khin RegularExpressValidator vo Form ca mnh v thit lp cho n
mt s thuc tnh sau:
ID: tn ca iu khin
ControlToValidate: tr n iu khin cn kim tra
Text(ErrorMessage): ni dung thng bo khi c li
ValidatorExpression: quy nh mu nhp liu nh l hm th, s in thoi
3. V d
Sau y s l mt v d v vic yu cu ngi s dng phi cp nht ng a ch ca
hm th.
Code 3: trang RegularExpressionValidator.aspx
<script runat="server">
void btnAccept_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
lblThongbao.Text = txtEmail.Text;
}
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
http://www.ebook.edu.vn
80
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>RegularExpressionValidator</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Email:<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="txtEmail"
ID="RequiredFieldValidator1" runat="server" ErrorMessage="Bn phi nhp a
ch hm th"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server"
ErrorMessage="Bn nhp khng ng nh dng hm th"
ControlToValidate="txtEmail"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([.]\w+)*"></asp:RegularExpressionValidator>
<br />
<asp:Button ID="btnAccept" OnClick="btnAccept_Click" runat="server"
Text="Accept" />
<asp:Label ID="lblThongbao" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
1. ngha
iu khin CompareValidator c 3 kiu khc nhau kim tra gi tr nhp:
http://www.ebook.edu.vn
81
2. Cch s dng
Bn a iu khin CompareValidator vo Form v thit lp cho n mt s thuc tnh
sau:
3. V d
V d 4 sau s yu cu nhp vo ngy sinh, nu ngi s dng nhp vo khng ng
d liu dng ngy th s c li thng bo.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>CompareValidator</title>
</head>
<body>
<form id="form1" runat="server">
<div>
http://www.ebook.edu.vn
82
</div>
</form>
</body>
</html>
Code 5 trang
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="CompareValidator.aspx.cs" Inherits="CompareValidator" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>CompareValidator</title>
http://www.ebook.edu.vn
83
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
V. iu khin CustomValidator
1.
ngha
http://www.ebook.edu.vn
84
2. Cch s dng v V d
CustomValidator c 3 thuc tnh hay s dng l:
CustomValidator h tr 1 s kin
ServerValidate: S kin c a ra khi CustomValidator thc hin kim chng.
V d sau s s dng s kin ServerValidate kim tra di ca chui c nhp
trong iu khin TextBox, nu ngi nhp, nhp vo chui c di ln hn 20 k t th
iu khin CustomValidator s a ra thng bo li.
V d:
Code 6 trang CustomValidator.aspx
<%@ Page Language="C#" %>
<script runat="server">
void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs e)
{
if (e.Value.Length > 20)
e.IsValid = false;
else
e.IsValid = true;
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
http://www.ebook.edu.vn
85
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>CustomValidator</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
http://www.ebook.edu.vn
86
IsValid: Din t vic kim chng cho kt qu thnh cng hoc sai.
Code 7.
<%@ Page Language="C#" %>
<script runat="server">
void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs e)
{
if (e.Value.Length > 20)
e.IsValid = false;
else
e.IsValid = true;
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>CustomValidator</title>
<script language="javascript" type="text/javascript">
function valComments_ClientValidate(source, args)
{
if (args.Value.length > 20)
args.IsValid = false;
else
http://www.ebook.edu.vn
87
args.IsValid = true;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
1. ngha
http://www.ebook.edu.vn
88
2. cch s dng
sau:
3. v d
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ValidationSummary</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ValidationSummary ID="ValSummary" runat="server" />
<table>
<tr>
http://www.ebook.edu.vn
89
<td>
<asp:Label ID="Label1" runat="server" Text="H
tn"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtHoten" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server"
ErrorMessage="Bn phi nhp h tn"
ControlToValidate="txtHoten">*(Yu cu)</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label2" runat="server"
Text="Email"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2"
runat="server"
ErrorMessage="Bn phi nhp hm th"
ControlToValidate="txtEmail">*(Yu cu)</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1" runat="server"
ErrorMessage="Hm th bn nhp khng ng nh dng"
ControlToValidate="txtEmail"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td colspan="2">
http://www.ebook.edu.vn
90
</div>
</form>
</body>
</html>
Code 8
Chy v d trn nu ta khng nhp d liu cho cc trng n s thng bo li nh sau:
Code 9
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="ValidationSummary.aspx.cs" Inherits="ValidatorSummary" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
http://www.ebook.edu.vn
91
<title>ValidationSummary</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ValidationSummary ShowMessageBox="true" ShowSummary="false"
ID="ValSummary" runat="server" />
<table>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="H
tn"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtHoten" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server"
http://www.ebook.edu.vn
92
ControlToValidate="txtEmail"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="Button1" runat="server" Text="Accept" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Kt xut ca n:
http://www.ebook.edu.vn
93
Code 10 LenghtValidator.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace myControls
{
public class LengthValidator : BaseValidator
{
int _maximumLength = 0;
http://www.ebook.edu.vn
94
Code 11
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="LengthValidator.aspx.cs" Inherits="LengthValidator" %>
<%@ Register TagPrefix="validator" Namespace="myControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
http://www.ebook.edu.vn
95
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Use LenghtValidator</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Ghi ch"></asp:Label>
<br />
<asp:TextBox ID="txtghichu" runat="server" Height="67px"
TextMode="MultiLine"
Width="176px"></asp:TextBox>
<validator:LengthValidator ID="validatorLength"
ControlToValidate="txtghichu" runat="server" ErrorMessage="Phi nh hn 20 k
t" MaximumLength="20"></validator:LengthValidator>
<br />
<asp:Button ID="Button1" runat="server" Text="Accept" Width="85px" />
</div>
</form>
</body>
</html>
http://www.ebook.edu.vn
96
I. File Upload.
iu khin FileUpload cho php ngi s dng Upload file t chnh ng dng Web ca
mnh.
File sau khi Upload c th lu tr 1 ni no c th l trn cng hay trong
Database.
iu khin FileUpload h tr cc thuc tnh sau:
Thuc tnh
ngha
Enable
FileBytes
FileContent
FileName
Ly tn file c Upload
HasFile
PostedFile
Enables you to get the uploaded file wrapped in the HttpPostedFile object.
Focus: Enables you to shift the form focus to the FileUpload control.
Thuc tnh PostedFile ca iu khin FileUpload cho php ly thng tin t File upload
c bao bc trong i tng HttpPostedFile. i tng ny s a thm thng tin v Upload
file.
Lp HttpPostedFile gm cc thuc tnh sau:
http://www.ebook.edu.vn
97
http://www.ebook.edu.vn
98
</form>
</body>
</html>
Code 1b.Fileupload.aspx.cs
using System;
using System.Data;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_PreRender()
{
string upload_folder = MapPath("~/Upload/");
DirectoryInfo dir = new DirectoryInfo(upload_folder);
listImage.DataSource = dir.GetFiles();
listImage.DataBind();
}
bool CheckFileType(string fileName)
{
string ext = Path.GetExtension(fileName);
switch (ext.ToLower())
{
case ".gif":
return true;
case ".png":
return true;
http://www.ebook.edu.vn
99
case ".jpg":
return true;
case ".jpeg":
return true;
default:
return false;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if(CheckFileType(FileUpload1.FileName))
{
string filepath = "~/Upload/" + FileUpload1.FileName;
FileUpload1.SaveAs(MapPath(filepath));
}
}
}
}
Gii thch v d trn: Trong s kin Button1_Click Kim tra c tn ti File Upload?
Nu ng th kim tra kim tra file upload c phi ng nh dng ca nh khng bng hm
CheckFileType nu ng th s thc hin vic ghi file ln server vi phng thc SaveAs ca
iu khin FileUpload.
Code 2.
http://www.ebook.edu.vn
100
Cc thuc tnh:
Thuc tnh
ngha
DayNameFormat
NextMonthText
http://www.ebook.edu.vn
101
NextPrevFormat
PreMonthText
SelectedDate
SelectedDates
SelectionMode
SelectMonthText
SelectWeekText
ShowdayHeader
ShowNextPrevMonth
Cho php hin th hay khng lin kt n thng tip theo hoc thng
trc .
ShowTitle
TitleFormat
TodaysDate
Cc S kin.
V d sau s trnh by cch ly thng tin khi chng ta la chn nhiu ngy trn i
tng Calendar.
http://www.ebook.edu.vn
102
http://www.ebook.edu.vn
103
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
bllresult.DataSource = calendar1.SelectedDates;
bllresult.DataBind();
}
}
Kt xut ca v d 3
To mt Popup Datepicker
Trong phn ny bn s hc cch s dng iu khin Calendar kt hp vi Javacript
to mt Pop-up Date picker nh trong hnh di y:
http://www.ebook.edu.vn
104
Code 4. popupdatepicker.aspx
<%@ Page Language="C#" %>
<script runat="server">
protected void calEventDate_SelectionChanged(object sender, EventArgs e)
{
txtEventDate.Text = calEventDate.SelectedDate.ToString("d");
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
lblResult.Text = "Bn chn: " + txtEventDate.Text;
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
http://www.ebook.edu.vn
105
function displayCalendar()
{
var datePicker = document.getElementById('datePicker');
datePicker.style.display = 'block';
}
</script>
<style type="text/css">
#datePicker
{
display:none;
position:absolute;
border:solid 2px black;
background-color:white;
}
.content
{
width:400px;
background-color:white;
margin:auto;
padding:10px;
}
html
{
background-color:silver;
}
</style>
</head>
<body>
http://www.ebook.edu.vn
106
ngha
AdvertisementFile
AlternateTextField
DataMenber
DataSource
http://www.ebook.edu.vn
107
DataSourceID
ImgUrlFile
KeywordFilter
NavigateUrlField
Target
S kin
http://www.ebook.edu.vn
108
<div id="right">
<div class="box">
http://www.ebook.edu.vn
109
<asp:AdRotator ID="AdRotator1"
AdvertisementFile="~/App_Data/AdList.xml" KeywordFilter="right" runat="server"
/>
</div>
<div class="box">
<asp:AdRotator ID="AdRotator2"
AdvertisementFile="~/App_Data/AdList.xml" KeywordFilter="right" runat="server"
/>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
Ni dung File XML
Code 5b.
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
<Ad>
<ImageUrl>~/Advertisement/images/banner.png</ImageUrl>
<Width>782</Width>
<Height>100</Height>
<NavigateUrl>http://www.itechpro.com.vn</NavigateUrl>
<AlternateText>Cong ty cong nghe cao iTechPro</AlternateText>
<Impressions>50</Impressions>
<Keyword>banner</Keyword>
</Ad>
<Ad>
http://www.ebook.edu.vn
110
<ImageUrl>~/Advertisement/images/banner2.gif</ImageUrl>
<Width>782</Width>
<Height>100</Height>
<NavigateUrl>http://www.itechpro.com.vn</NavigateUrl>
<AlternateText>Cong ty cong nghe cao iTechPro</AlternateText>
<Impressions>50</Impressions>
<Keyword>banner</Keyword>
</Ad>
<Ad>
<ImageUrl>~/Advertisement/images/anh1.gif</ImageUrl>
<Width>150</Width>
<Height>150</Height>
<NavigateUrl>http://www.itechpro.com.vn</NavigateUrl>
<AlternateText>Box Advertisement 1</AlternateText>
<Impressions>50</Impressions>
<Keyword>right</Keyword>
</Ad>
<Ad>
<ImageUrl>~/Advertisement/images/anh1.gif</ImageUrl>
<Width>150</Width>
<Height>150</Height>
<NavigateUrl>http://www.itechpro.com.vn</NavigateUrl>
<AlternateText>Box Advertisement 1</AlternateText>
<Impressions>50</Impressions>
<Keyword>right</Keyword>
</Ad>
<Ad>
<ImageUrl>~/Advertisement/images/anh2.gif</ImageUrl>
http://www.ebook.edu.vn
111
<Width>150</Width>
<Height>150</Height>
<NavigateUrl>http://www.itechpro.com.vn</NavigateUrl>
<AlternateText>Box Advertisement 1</AlternateText>
<Impressions>50</Impressions>
<Keyword>right</Keyword>
</Ad>
<Ad>
<ImageUrl>~/Advertisement/images/anh3.gif</ImageUrl>
<Width>150</Width>
<Height>150</Height>
<NavigateUrl>http://www.itechpro.com.vn</NavigateUrl>
<AlternateText>Box Advertisement 1</AlternateText>
<Impressions>50</Impressions>
<Keyword>right</Keyword>
</Ad>
<Ad>
<ImageUrl>~/Advertisement/images/anh4.gif</ImageUrl>
<Width>150</Width>
<Height>150</Height>
<NavigateUrl>http://www.itechpro.com.vn</NavigateUrl>
<AlternateText>Box Advertisement 1</AlternateText>
<Impressions>50</Impressions>
<Keyword>right</Keyword>
</Ad>
<Ad>
<ImageUrl>~/Advertisement/images/anh5.gif</ImageUrl>
<Width>150</Width>
http://www.ebook.edu.vn
112
<Height>150</Height>
<NavigateUrl>http://www.itechpro.com.vn</NavigateUrl>
<AlternateText>Box Advertisement 1</AlternateText>
<Impressions>50</Impressions>
<Keyword>right</Keyword>
</Ad>
<Ad>
<ImageUrl>~/Advertisement/images/anh6.gif</ImageUrl>
<Width>150</Width>
<Height>150</Height>
<NavigateUrl>http://www.itechpro.com.vn</NavigateUrl>
<AlternateText>Box Advertisement 1</AlternateText>
<Impressions>50</Impressions>
<Keyword>right</Keyword>
</Ad>
</Advertisements>
Cch thc hin bn a XML c cu trc nh code 5b, sau trong trang
AdRotatorXML.aspx bn a iu khin AdRotator vo v t cho n hai thuc tnh
AdvertisementFile ch n File XML bn va to, v thuc tnh KeywordFilter theo th
Keyword trong file XML.
IV.
iu khin MultiView cho php bn n hoc hin cc phn khc nhau ca trang Web,
iu khin ny tin ch khi bn to mt TabPage. N thc s tin ch khi bn mun chia 1
trang web c di ln thnh cc phn hin th
iu khin MultiView cha ng 1 hoc nhiu iu khin View, bn s dng Multiview
la chn cc iu khin View trnh by.
iu khin MultiView h tr cc thuc tnh.
http://www.ebook.edu.vn
113
Cch s dng
1. hin th nh mt TabPage
Khi bn s dng MultiView kt hp vi iu khin Menu bn c th to mt TabPage
V d sau s hng dn bn to mt TabPage t 2 iu khin Menu v MultiView
Code 6a.
<%@ Page Language="C#" %>
<script runat="server">
void Menu1_MenuItemClick(object sender, MenuEventArgs e)
{
int index = Int32.Parse(e.Item.Value);
MultiView1.ActiveViewIndex = index;
}
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MultiView1.ActiveViewIndex = 0;
}
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
http://www.ebook.edu.vn
114
<head runat="server">
<title>Create a TabView</title>
<style type="text/css">
html
{
background-color:silver;
}
.tabs
{
position:relative;
top:1px;
left:10px;
}
.tab
{
border:solid 1px black;
background-color:#eeeeee;
padding:2px 10px;
}
.selectedTab
{
background-color:white;
border-bottom:solid 1px white;
}
.tabContents
{
border:solid 1px black;
padding:10px;
http://www.ebook.edu.vn
115
background-color:white;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Menu ID="Menu1"
OnMenuItemClick="Menu1_MenuItemClick" runat="server"
Orientation="Horizontal" StaticMenuItemStyle-CssClass="tab"
StaticSelectedStyle-CssClass="selectedTab" CssClass="tabs">
<Items>
<asp:MenuItem Text="Tab 1" Value="0"
Selected="true"></asp:MenuItem>
<asp:MenuItem Text="Tab 2" Value="1"></asp:MenuItem>
<asp:MenuItem Text="Tab 3" Value="2"></asp:MenuItem>
</Items>
</asp:Menu>
<div class="tabContents">
<asp:MultiView ID="MultiView1" runat="server">
<asp:View ID="view1" runat="server">
Day la View 1<br />
Day la View 1<br />
Day la View 1<br />
Day la View 1<br />
Day la View 1<br />
Day la View 1<br />
</asp:View>
http://www.ebook.edu.vn
116
http://www.ebook.edu.vn
117
Code 7.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultipartView.aspx.cs"
Inherits="MiltipartView" %>
<script runat="server">
void View3_Active(object sender, EventArgs e)
{
lblRHoten.Text = txtHoten.Text;
lblRCMT.Text = txtCMT.Text;
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
http://www.ebook.edu.vn
118
<div>
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View ID="View1" runat="server">
<asp:Label ID="lblHoten" runat="server" Text="Nhp h
tn"></asp:Label>
<asp:TextBox ID="txtHoten" runat="server"
Width="198px"></asp:TextBox><br />
<asp:Button ID="btnNext1" runat="server"
CommandName="NextView" Text="Next" Width="98px" /></asp:View>
<asp:View ID="View2" runat="server">
<asp:Label ID="lblCMT" runat="server" Text="Nhp s
CMT"></asp:Label>
<asp:TextBox ID="txtCMT" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnNext2" runat="server"
CommandName="NextView" Text="Next" Width="99px" /></asp:View>
<asp:View ID="View3" OnActivate="View3_Active" runat="server">
<asp:Label ID="Label1" runat="server" Text="H
tn:"></asp:Label>
<asp:Label ID="lblRHoten" runat="server"
Text="Label"></asp:Label><br />
<asp:Label ID="Label2" runat="server" Text="S
CMT:"></asp:Label>
<asp:Label ID="lblRCMT" runat="server"
Text="Label"></asp:Label></asp:View>
</asp:MultiView></div>
</form>
</body>
</html>
Trong v d trn 2 button u thit lp thuc tnh CommandName c gi tr l NextView, do
iu khin MultiView h tr lnh NextView ln khi nhn vo 2 Button th lnh NextView
c thc hin v kch hot View tip theo n View 3 vi s kin OnActive gi hm
View3_Active v thc hin ly v gi tr ca hai TextBox v gn vo 2 Label tng ng.
119
Cc thuc tnh.
http://www.ebook.edu.vn
120
Wizard: cho php bn ly thng tin iu khin Wizard cha trong WizardStep.
StepType l thuc tnh quan trng nht ca Wizard, thuc tnh no xc nh WizardStep
c a ra nh th no, mc nh l Auto
V d:
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="WirardControl.aspx.cs" Inherits="_Default" %>
<script runat="server">
void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
lblbiet.Text = txt1.Text;
lblkhoahoc.Text = txt2.Text;
http://www.ebook.edu.vn
121
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Wizard </title>
<style type="text/css">
.wizard{border:solid 1px black;font:14px
Verdana,width:800px;height:300px;}
.header{color:gray;font:bold 18px Verdana,}
.sideBar{background-color:#eeeeee;padding-left:10px;width:200px;
height:23px;}
.sideBar a{text-decoration:none;}
.step{padding:10px;}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
http://www.ebook.edu.vn
122
http://www.ebook.edu.vn
123
</body>
</html>
Gii thch v d:
Trn v d ta a vo 4 WizardStep, chng trnh s thc hin trnh t theo cc bc
v kt thc vi vic nhn nt Finish WizardStep3(c thit lp thuc tnh
StepType=Finish) thng qua hm Wizard1_FinishButtonClick sau khi thc hin hm ny
n s chuyn sang v hin th ni dung cng vic cn thc hin thng 2 iu khin label trn
WizardStep4 v iu khin ny c thit lp thuc tnh StepType=Complete.
Code 1.
<%@ Master Language="C#" AutoEventWireup="true"
CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>MasterPage</title>
<style type="text/css">
html{ background-color:#e5e5e5; font-family:Verdana;}
http://www.ebook.edu.vn
124
code 2
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" %>
<asp:Content ID="contentleft" ContentPlaceHolderID="contentplace1"
runat="server">
Trinh bay menu Left<br />
http://www.ebook.edu.vn
125
<system.web>
<pages masterPageFile="~/SimpleMasterPage.master" />
</system.web>
http://www.ebook.edu.vn
126
Trang Findcontrol.master
<%@ Master Language="C#" AutoEventWireup="true"
CodeFile="Findcontrol.master.cs" Inherits="Findcontrol" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Findcontrol</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblTitle" runat="server" /><br />
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
Trang Findcontrol.aspx
<%@ Page Language="C#" MasterPageFile="~/Findcontrol.master"%>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
http://www.ebook.edu.vn
127
Trang Expose.master
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Expose.master.cs"
Inherits="Expose" %>
<script runat="server">
public string BodyTitle
{
get { return lblBody.Text; }
set { lblBody.Text = value; }
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
http://www.ebook.edu.vn
128
<head runat="server">
<title>Expose MasterPage Property</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1><asp:Label ID="lblBody" runat="server"
Text="iTechPro"></asp:Label></h1>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
Trang Expose.aspx
<%@ Page Language="C#" MasterPageFile="~/Expose.master" AutoEventWireup="true"
%>
<%@ MasterType VirtualPath="~/Expose.master" %>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Master.BodyTitle = "Trung tam dao tao cong nghe cao iTechPro";
}
}
</script>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
Runat="Server">
http://www.ebook.edu.vn
129
skin files
Hnh 1
http://www.ebook.edu.vn
130
bc 2: hp thoi Add New Item hin ra bn chn Skin File v t tn Skin ca mnh vo
hp Name v nhn vo nt Add nh hnh sau:
Hnh 2
bc 3: hp thoi thng bo hin ra bn chn YES.
http://www.ebook.edu.vn
131
http://www.ebook.edu.vn
132
http://www.ebook.edu.vn
133
V d:
File simple.css
html{background-color:gray;font:14px Georgia,Serif;}
.content{margin:auto;width:600px;border:solid 1px black;backgroundcolor:White;padding:10px;}
h1{color:Gray;font-size:18px;border-bottom:solid 1px orange;}
label{font-weight:bold;}
input{background-color:Yellow;border:double 3px orange;}
.button{background-color:#eeeeee;}
File skintotheme.aspx
<%@ Page Language="C#" Theme="blue" AutoEventWireup="true"
CodeFile="skintotheme.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>SIMPLE CSS</title>
http://www.ebook.edu.vn
134
</head>
<body>
<form id="form1" runat="server">
<div class="content">
<h1>Registration Form</h1>
<asp:Label id="lblFirstName" Text="First Name:"
AssociatedControlID="txtFirstName" Runat="server" /><br />
<asp:TextBox id="txtFirstName" Runat="server" /><br /><br />
<asp:Label id="lblLastName" Text="Last Name:"
AssociatedControlID="txtLastName" Runat="server" /><br />
<asp:TextBox id="txtLastName" Runat="server" /><br /><br />
<asp:Button id="btnSubmit" Text="Submit Form" CssClass="button"
Runat="server" />
</div>
</form>
</body>
</html>
http://www.ebook.edu.vn
135
Code 1: Caculator.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Caculator.ascx.cs"
Inherits="Caculator" %>
<asp:Label ID="Label1" runat="server" Text="Nhp a:"></asp:Label>
<asp:TextBox ID="txta" runat="server"></asp:TextBox>
<asp:Label ID="Label2" runat="server" Text="Nhp b:"></asp:Label>
<asp:TextBox ID="txtb" runat="server"></asp:TextBox>
<hr />
<asp:Button ID="btnsum" OnCommand="Calculator" CommandName="cal"
CommandArgument="sum" runat="server" Text="+" Width="45px" />
http://www.ebook.edu.vn
136
Code 2 Caculator.ascx.cs
using System;
public partial class Caculator : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
http://www.ebook.edu.vn
137
{
}
protected void Calculator(object sender, CommandEventArgs e)
{
if (e.CommandName == "cal")
{
switch (e.CommandArgument.ToString())
{
case "sum":
lblresult.Text = Convert.ToString(int.Parse(txta.Text) +
int.Parse(txtb.Text));
break;
case "sub":
lblresult.Text = Convert.ToString(int.Parse(txta.Text) int.Parse(txtb.Text));
break;
case "mul":
lblresult.Text = Convert.ToString(int.Parse(txta.Text) *
int.Parse(txtb.Text));
break;
case "div":
{
if (int.Parse(txtb.Text) != 0)
lblresult.Text =
Convert.ToString(int.Parse(txta.Text) / int.Parse(txtb.Text));
}
break;
default:
//
break;
http://www.ebook.edu.vn
138
}
}
}
}
Code 3: Default.aspx
<%@ Page Language="C#" AutoEventWireup="true"
Inherits="_Default" %>
CodeFile="Default.aspx.cs"
http://www.ebook.edu.vn
139
</html>
S dng ch dn Reference
Khi bn load 1 Usercontrol vi phng thc Page.LoadControl(), UserControl c tr v nh
mt thc th ca lp System.Web.UI.WebControl. c ngha l bao gm tt c cc thuc tnh tu
bin, thuc tnh ny khng c sn nh vi trng hp Load UserControl ng.
Nu bn s dng Load UserControl ng bn cn p kiu ca UserControl v ng kiu trc khi
s dng cc thuc tn. ly mt tham chiu ti mt Usercontrol bn cn phi s dng ch dn
<%@ Reference %>
V d: bn mun thm d kin ca mi ngi xem h tng s dng ngn ng asp c bn hay
ngn ng asp.net ? V tu thuc vo mi ngi h s chn asp hay aspnet a ra hin th mt
UserControl.
Lu d liu tp trung
m bo ton vn d liu
Bo mt d liu
http://www.ebook.edu.vn
140
Hnh 1
http://www.ebook.edu.vn
141
Hnh 2
Hnh 3
http://www.ebook.edu.vn
142
Hnh 4
o
Hnh 5
Trong mn hnh ca VS s hin ra nh hnh 6 v bn thao tc to cc trng d liu
nh thao tc vi Access hay MSSQL 2000/2005
http://www.ebook.edu.vn
143
Hnh 6
using System;
using System.Data;
using System.Data.SqlClient;
http://www.ebook.edu.vn
144
bc 1: Ti kt ni
bc 3:M kt ni d liu
bc 5: ng kt ni
bc 6: in kt qu
http://www.ebook.edu.vn
145
1. Thuc tnh:
ConnectString: cha ng chui kt ni ti c s d liu
Database: Cha ng tn c s d liu trong chui kt ni ConnectString trn v bn
c th thay i c s d liu trong lc thc thi bng phng thc ChangeDataBase:
Sqlconn.ChangeDatabase(name_database_thaydoi);
Server: tn my ch bn tr ti
Connect Timeout: s thi gian(tnh bng giy) ch kt ni d liu mc nh l 15giy,
nu trong khong thi gian ny m vn cha kt ni xong mt li Connect Timeout c a
ra.
State: tr v trng thi ca i tng SqlConnection: bn c th kim tra trng thi
ca State nh sau
Response.Write(sqlconn.State)
http://www.ebook.edu.vn
146
http://www.ebook.edu.vn
147
V. i tng DataAdapter
OleDataAdapter c xem nh b c d liu t c s dliu ngun v in chng vo i
tng DataSet hay DataTable
Khai bo, khi to v gii phng i tng.
string ssql;
Khai bo i tng
Dim sqlcom As SqlCommand
Dim sqlconn As SqlConnection
Dim sqladapter As SqlDataAdapter
sqlconn.Open();
cch 1.
sqladapter = New OleDbDataAdapter(ssql, sqlconn)
sqlcom = New SqlCommand(ssql, sqlconn)
cch 2.
sqladapter = new SqlDataAdapter(sqlcom);
Gii phng i tng
sqladapter.Dispose();
Thuc tnh:
http://www.ebook.edu.vn
148
in d liu vo DataTable
public static DataTable FillDatatable(string ssql)
http://www.ebook.edu.vn
149
{
opendata();
DataTable datatable = new DataTable();
try
{
sqladapter = new SqlDataAdapter(ssql, sqlconn);
sqladapter.Fill(datatable);
sqladapter.Dispose();
}
finally
{
closedata();
}
closedata();
return datatable;
}
Thuc tnh Tables, dataset c dng cha danh sch cc i tng DataTable
V d:
private void button1_Click(object sender, EventArgs e)
{
http://www.ebook.edu.vn
150
http://www.ebook.edu.vn
151
152
dataset.Tables.RemoveAt(0);
phng thc Clear loi b tt c cc i tng trong DataTable
dataset.Tables.Clear();
De dem so dong du lieu trong bang ta co the thuc hien
int sodong=dataset.Tables[0].Rows.Count;
2. i tng DataTable
private void button1_Click(object sender, EventArgs e)
{
string strQuery = "select top 10 * from tblEmployees";
//khoi tao doi tuong DataTable
dataTable = new DataTable("Employees");
try
{
SqlDataAdapter sqlDataAdapter = new
SqlDataAdapter(strQuery, Connection.sqlConnection);
//dien du lieu vao datatable
sqlDataAdapter.Fill(dataTable);
sqlDataAdapter.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
//gan du lieu va dataGrid voi thuoc tinh DataSource
this.dataGridView1.DataSource = dataTable;
label1.Text= dataTable.TableName ;
}
http://www.ebook.edu.vn
153
// thuoc tinh DataRow tra ve cac mau tin dang chua trong doi tuong DataTable
private void button2_Click(object sender, EventArgs e)
{
if (dataTable != null)
{
string name = "";
foreach (DataRow dataRow in dataTable.Rows)
{
name += Convert.ToString(dataRow[1]) + "\n";
}
label1.Text = name;
}
}
//thuoc tinh Columns tra ve tap doi tuong DataColumn bao gom danh sach cot du
lieu cua bang chua trong doi tuong DataTable
private void button3_Click(object sender, EventArgs e)
{
if (dataTable != null)
{
string name = "";
foreach (DataColumn dataColumn in dataTable.Columns)
{
name += Convert.ToString(dataColumn.ColumnName) + "\n";
}
label1.Text = name;
}
}
154
Bc 1: to bng c s d liu
V d chng ta c mt bng d liu tblIntrodure gm cc trng:
pkIntrodureID
(int)
sTitle
(nvarchar(300)
sSummary
(nText)
iContent
(nText)
iPosition
(int)
Bc 2: to th tc StoreProcedure
http://www.ebook.edu.vn
155
@iPosition int
AS
update tblIntrodure set
sTitle=@sTitle, sSummary=@sSummary, sContent=@sContent,
iPosition=@iPosition
where pkIntrodureID=@pkIntrodureID
GO
spIntrodure_deletebyID - Th tc xo d liu
Create PROCEDURE spIntrodure_deletebyID
@pkIntrodureID int
AS
delete from tblIntrodure where pkIntrodureID=@pkIntrodureID
GO
namespace iTechPro.Modules.Introdure
{
public class IntrodureInfo
{
int _pkIntrodureID;
public int pkIntrodureID
{
get { return _pkIntrodureID; }
set { _pkIntrodureID = value; }
http://www.ebook.edu.vn
156
}
string _sTitle;
public string sTitle
{
get { return _sTitle; }
set { _sTitle = value; }
}
string _sImage;
public string sImage
{
get { return _sImage; }
set { _sImage = value; }
}
string _sSumary;
public string sSumary
{
get { return _sSumary; }
set { _sSumary = value; }
}
string _sComment;
public string sComment
{
get { return _sComment; }
set { _sComment = value; }
}
int _iPosition;
public int iPosition
http://www.ebook.edu.vn
157
{
get { return _iPosition; }
set { _iPosition = value; }
}
}
}
IntrodureDB.cs (cha tt c phng thc x l v ly d liu cho bng tblIntrodure)
using System;
using System.Data;
using System.Data.SqlClient;
using iTechPro.Library;
namespace iTechPro.Modules.Introdure
{
public class IntrodureDB : ExcuteDataHelper
{
public IntrodureDB()
{
//
// TODO: Add constructor logic here
//
}
public static void Delete(string _pkIntrodureID)
{
string[] parameters = new string[] { "@pkIntrodureID"};
string[] values = new string[] { _pkIntrodureID};
executeData("spIntrodure_deletebyID", parameters, values);
}
http://www.ebook.edu.vn
158
http://www.ebook.edu.vn
159
_introdure.sSumary = mydata.Rows[0]["sSumary"].ToString();
_introdure.sComment = mydata.Rows[0]["sComment"].ToString();
_introdure.sPage = mydata.Rows[0]["sPage"].ToString();
_introdure.sLang = mydata.Rows[0]["sLang"].ToString();
_introdure.iPosition =
int.Parse(mydata.Rows[0]["iPosition"].ToString());
return _introdure;
}
}
}
namespace iTechPro.Library
{
public class ExcuteDataHelper : iTechProData
{
//phuong thuc thuc thi du lieu(them moi, chinh sua, xoa) khi dua vao
mot tham so sql
#region executeData(string sql)"Thc thi d liu"
public static void executeData(string sql)
{
opendata();
sqlcom = new SqlCommand(sql, sqlconn);
try
http://www.ebook.edu.vn
160
{
sqlcom.ExecuteNonQuery();
closedata();
}
catch (Exception exp)
{
closedata();
HttpContext.Current.Response.Write(sql + "<br/>");
HttpContext.Current.Response.Write("C li trong qu trnh
thc thi " + exp.ToString());
}
}
#endregion
//phuong thuc thuc thi du lieu voi tham so dua vao
#region executeData(string store, string[] Parameter, string[] Values)
public static void executeData(string store, string[] Parameter,
string[] Values)
{
opendata();
sqlcom = new SqlCommand();
sqlcom.CommandText = store;
sqlcom.Connection = sqlconn;
sqlcom.CommandType = CommandType.StoredProcedure;
for (int i = 0; i < Parameter.Length; i++)
{
sqlcom.Parameters.AddWithValue(Parameter[i], Values[i]);
}
try
{
http://www.ebook.edu.vn
161
sqlcom.ExecuteNonQuery();
closedata();
}
catch (DataException exp)
{
sqlconn.Close();
HttpContext.Current.Response.Write(exp.ToString());
}
}
#endregion
}
}
Trong lp ny chng ta c 2 phng thc thc thi d liu c th l thm mi, chnh sa
hay xo d liu void executeData(string sql) cho php bn thc thi d liu vi mt chui sql a
vo cn executeData(string store, string[] Parameter, string[] Values) s thc thi d liu vi hm
th tc t SQL truyn vo vi hai mng gi tr v tham s v lp ny ny tha k t lp dn xut
iTechProData.cs
Lp iTechProData.cs
using System;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace iTechPro.Library
{
public class iTechProData
{
#region khai bao bien
protected string ssql;
http://www.ebook.edu.vn
162
http://www.ebook.edu.vn
163
http://www.ebook.edu.vn
164
finally
{
closedata();
}
return datatable;
}
}
}
Code: adminIntrodure.aspx
<%@ Page Language="C#" MasterPageFile="~/admin.master" AutoEventWireup="true"
CodeFile="adminIntrodure.aspx.cs" Inherits="Desktop_Introdure_adminIntrodure"
Title="Admin - Introdure" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
Runat="Server">
<!--Trinh bay du lieu-->
<table cellpadding="0" cellspacing="0" width="100%" style="padding-right:3px;
height:390px">
<tr>
<td style="padding:15px 15px 15px 15px" valign="top">
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td align="left" class="hcubiufontlarger">Gii thiu</td>
</tr>
<tr><td style="height:15px;"></td></tr>
<!--start them moi-->
<tr>
http://www.ebook.edu.vn
165
<td align="left">
<asp:Panel ID="panelupdate" Width="100%" runat="Server"
Visible="false">
<table width="100%" style="padding-left:20px;">
<tr>
<td colspan="2"><b>Cp nht thng tin gii thiu</b></td>
</tr>
<tr><td style="width: 78px; height:15px;"></td></tr>
<tr>
<td align="left" style="width: 78px">Tiu </td>
<td align="left"><input type="text" name="txtTitle"
id="txtTitle" runat="server" style="width: 329px" /></td>
</tr>
<tr>
<td valign="middle" align="left" style="width: 78px">Tm
tt</td>
<td align="left">
<asp:TextBox ID="txtTomtat" runat="server"
TextMode="MultiLine"></asp:TextBox>
</td>
</tr>
<tr>
<td align="left" style="height: 88px; width: 78px;">Ni
dung</td>
<td align="left" style="height: 88px">
<asp:TextBox ID="txtNoidung" runat="server"
TextMode="MultiLine" />
</td>
</tr>
<tr>
<td align="left">V tr</td>
http://www.ebook.edu.vn
166
<td align="left">
<asp:TextBox ID="txtvitri" runat="server"
Text="1"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="txtvitri"
ErrorMessage="V tr phi l kiu s" MaximumValue="100"
MinimumValue="0" Type="Integer"></asp:RangeValidator></td>
</tr>
<tr><td style="width: 78px; height:15px;"></td></tr>
<tr>
<td colspan="2" align="left">
<asp:Button ID="btnaccept" runat="server" Text="Ghi"
Width="100px" OnClick="btnaccept_Click"/>
<asp:Button ID="btcancel" runat="server" Text="B qua"
Width="100px" OnClick="btcancel_Click" />
<asp:Label ID="lblidintro" runat="server" Text=""
Visible="false"></asp:Label></td>
</tr>
</table>
</asp:Panel>
<!--End them moi-->
</td>
</tr>
<tr>
<td
style="height:5px;"></td>
</tr>
<asp:Panel ID="panelview" runat="server">
<tr>
<td align="left" style="padding-bottom:3px;"><asp:LinkButton
ID="btnaddnew" CssClass="linkbutton" runat="server" Text="Thm mi"
OnClick="btnaddnew_Click" /></td>
</tr>
http://www.ebook.edu.vn
167
<tr>
<td valign="top" align="left">
<asp:DataGrid id="gridintro" runat="server"
BorderColor="black"
Width="100%"
BorderWidth="1"
CellPadding="3"
Font-Size="10pt"
HeaderStyle-BackColor="#aaaadd"
OnItemCommand="gridintro_OnItemCommand"
AutoGenerateColumns="false">
<HeaderStyle BackColor="#AAAADD"></HeaderStyle>
<Columns>
<asp:TemplateColumn HeaderStyle-HorizontalAlign="Center" ItemStyleHorizontalAlign="Center" HeaderStyle-Width="80px" HeaderText="STT">
<ItemTemplate>
<%#Container.ItemIndex +1 %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn HeaderStyle-HorizontalAlign="Left" ItemStyleHorizontalAlign="Left" DataField="sTitle" ReadOnly="true" HeaderText="Tiu
"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="V tr" ItemStyleHorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderStyleWidth="100px" ItemStyle-Width="100px" ItemStyle-Height="24px" >
<ItemTemplate>
<asp:TextBox ID="txtVitri" Width="39px" runat="server"
Text='<%#Eval("iPosition") %>' />
</ItemTemplate>
</asp:TemplateColumn>
http://www.ebook.edu.vn
168
http://www.ebook.edu.vn
169
<tr><td style="height:30px;"></td></tr>
</table>
</asp:Content>
Code adminIntrodure.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using iTechPro.Library;
using iTechPro.Modules.Introdure;
public partial class Desktop_Introdure_adminIntrodure : System.Web.UI.Page
{
string ssql;
void Loaddatagrid()
{
ssql = "select pkIntrodureID,sTitle,iPosition from tblIntrodure";
DatagridHelper.fill_datagrid(gridintro, ssql, "pkIntrodureID");
foreach (DataGridItem item in this.gridintro.Items)
{
LinkButton lbn =
(LinkButton)this.gridintro.Items[item.ItemIndex].FindControl("Delete");
lbn.Attributes.Add("onclick", "javascript:return confirm('Bn c
chc chn xo mc gii thiu ny')");
}
http://www.ebook.edu.vn
170
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Loaddatagrid();
}
}
private IntrodureInfo Getcontent()
{
IntrodureInfo intro = new IntrodureInfo();
try
{
intro.pkIntrodureID = int.Parse(lblidintro.Text);
}
catch
{
}
intro.sTitle = txtTitle.Value;
intro.sSumary = txtTomtat.Text;
intro.sContent = txtNoidung.Text;
intro.iPosition = int.Parse(txtvitri.Text);
return intro;
}
protected void btnaddnew_Click(object sender, EventArgs e)
{
panelupdate.Visible = true;
panelview.Visible = false;
http://www.ebook.edu.vn
171
txtNoidung.Text = "";
txtTitle.Value = "";
this.txtTomtat.Text = "";
txtvitri.Text = "1";
btnaccept.Text = "Ghi";
}
protected void gridintro_OnItemCommand(object sender,
DataGridCommandEventArgs e)
{
lblidintro.Text = e.CommandArgument.ToString();
if (e.CommandName == "Edit")
{
IntrodureInfo introdure = IntrodureDB.Getinfo(lblidintro.Text);
txtTitle.Value = introdure.sTitle;
txtTomtat.Text = introdure.sSumary;
txtvitri.Text = introdure.iPosition.ToString();
txtNoidung.Text = introdure.sContent;
btnaccept.Text = "Cp nht";
panelupdate.Visible = true;
panelview.Visible = false;
}
else
{
IntrodureDB.Delete(lblidintro.Text);
Loaddatagrid();
}
}
protected void btnaccept_Click(object sender, EventArgs e)
http://www.ebook.edu.vn
172
{
IntrodureInfo introdure = Getcontent();
if (btnaccept.Text == "Ghi")
{
IntrodureDB.Insert(introdure);
}
else
{
IntrodureDB.Update(introdure);
}
panelupdate.Visible = false;
panelview.Visible = true;
Loaddatagrid();
}
protected void btcancel_Click(object sender, EventArgs e)
{
panelview.Visible = true;
panelupdate.Visible = false;
Loaddatagrid();
}
protected void lbncapnhatvitri_Click(object sender, EventArgs e)
{
foreach (DataGridItem item in gridintro.Items)
{
TextBox txt =
(TextBox)this.gridintro.Items[item.ItemIndex].FindControl("txtVitri");
IntrodureDB.UpdateIndex(gridintro.DataKeys[item.ItemIndex].ToString(),
txt.Text);
http://www.ebook.edu.vn
173
}
}
}
I. iu khin DropdownList
ln
Cho php hin th mt danh sch cc la chn, ngui s dng ch chn mt la chn 1
V d:
Bn to mt lp phc v a d liu vo DropDownList nh sau:
s dng lp ny bn to 1 trang aspx v trong phn code behind bn nhp khu gi
iTechPro.Library, trong trong s kin Load ca trang bn gi nh sau
http://www.ebook.edu.vn
174
Code 9.1
protected void Page_Load(object sender, EventArgs e)
{
DropdownListHelper.Fillcombobox(DropDownList1, "tblIntrodure",
"sTitle", "pkIntrodureID");
}
Kt qu ca chng trnh s nh sau:
Hnh 1
s dng s kin OnSelectedIndexchanged bn cn thm vo cho DropDownList
thuc tnh AutoPostBack v thit lp cho n gi tr l true
Code chi tit
Trang dropdownlist.aspx
Code 9.2
<%@ Page Language="C#" AutoEventWireup="true"
Inherits="_Default" %>
CodeFile="dropdownlist.aspx.cs"
http://www.ebook.edu.vn
175
</asp:DropDownList><hr />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
Trang dropdownlist.aspx.cs
Code 9.3
using System;
using iTechPro.Library;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropdownListHelper.Fillcombobox(DropDownList1, "tblIntrodure",
"sTitle", "pkIntrodureID");
}
}
protected void DropDownList1_Changed(object sender, EventArgs e)
{
Label1.Text = "Text:" + DropDownList1.SelectedItem.Text + "<br>gi
tri:" + DropDownList1.SelectedValue.ToString();
}
}
http://www.ebook.edu.vn
176
(int)
sContent
(nvarchar(100))
iVote
(int)
iPosition
(int)
http://www.ebook.edu.vn
177
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="navcontain">
<b>Bn bit n iTechPro qua:</b><br />
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
</asp:RadioButtonList><hr />
<asp:LinkButton ID="lbnVote" OnClick="lbnVote_Click" Text="Vote"
runat="server" />
<hr />
Bn chn: <asp:Label runat="server" ID="lblResult" />
</div>
</form>
</body>
</html>
Trang radiobuttonlist.aspx.cs
Code 9.5
using System;
using iTechPro.Library;
public partial class radiobuttonlist : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListControlHelper.fillRadioButtonList(RadioButtonList1,
"tblSurveyAnswer", "sContent", "pkAnswerID");
http://www.ebook.edu.vn
178
}
}
protected void lbnVote_Click(object sender, EventArgs e)
{
this.lblResult.Text = RadioButtonList1.SelectedItem.Text + "<br> v
gi tr ca n l:" + RadioButtonList1.SelectedItem.Value;
}
}
Bn thy Code 9.6 lp radiobuttonlist.aspx.cs c nhp khu gi iTechPro.Library c s
dng phng thc fillRadioButtonList t lp ListControlHelper vi 4 i s tng ng nh
code cui chng trnh
Kt xut ca chng trnh
Hnh 3
179
http://www.ebook.edu.vn
180
http://www.ebook.edu.vn
181
Hnh 4
IV. S dng iu khin CheckBoxList
Ging vi iu khin RadioButtonList nhng n cho php ngi s dng chn la nhiu
phn t.
Code 9.9
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="checkBoxList.aspx.cs"
Inherits="checkBoxList" %>
Code 9.10
using System;
http://www.ebook.edu.vn
182
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTechPro.Library;
public partial class checkBoxList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListControlHelper.fillCheckBoxList(CheckBoxList1,
"tblSurveyAnswer", "sContent", "pkAnswerID");
}
}
protected void btnVote_Click(object sender, EventArgs e)
{
lblresult.Text = "";
for(int i = 0 ;i<CheckBoxList1.Items.Count;i++)
{
if (CheckBoxList1.Items[i].Selected == true)
{
lblresult.Text += "<li>" + CheckBoxList1.Items[i].Text +
"</li>";
}
}
}
}
http://www.ebook.edu.vn
183
btnVote_Click c thc hin khi bn nhn vo nt Vote trn trang, phng thc ny s
duyt t Item u n ht trong CheckBoxList v kim tra nu Item c chn th chng
ta s ly gi tr
Kt xut ca chng trnh
Code 9.11
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="BulletList.aspx.cs"
Inherits="BulletListItem" %>
http://www.ebook.edu.vn
184
Code 9.12
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTechPro.Library;
public partial class BulletListItem : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListControlHelper.fillBulletList(BulletedList1, "tblSurveyAnswer",
"sContent", "pkAnswerID");
}
}
}
Kt xut ca chng trnh
http://www.ebook.edu.vn
185
Source=.\SQLEXPRESS;
Security=True;user
</connectionStrings>
Bn to mt trang SimpleGridview.aspx v a vo mt iu khin SqlDataSource v
in vo n cc thuc tnh nh sau:
http://www.ebook.edu.vn
186
Code 10.1
<%@
Page
Language="C#"
AutoEventWireup="true"
CodeFile="SimpleGridview.aspx.cs" Inherits="_Default" %>
<!DOCTYPE
html
PUBLIC
"-//W3C//DTD
XHTML
1.0
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Transitional//EN"
ConnectionString="<%$
ConnectionStrings:Gridview
%>"
SelectCommand="select
*
runat="server"></asp:SqlDataSource>
from
tblIntrodure"
ID="SqlDataSource1"
</div>
</form>
</body>
</html>
Nh bn thy trong v d trn i tng SqlDatasource cha chi kt ni String c
ly ra t file web.config v thuc tnh selectCommand s a vo mt chui sql dng select
ly tt c d liu trong bng tblIntrodure
V
iu
khin
GridView
DataSourceID=_tn_sqlDatasource.
ca
http://www.ebook.edu.vn
187
ta
in
vo
thuc
tnh
Sorting Data
Bn c th trnh by sp xp d liu trong GridView vi thuc tnh AllowSorting
V d: cng vi v d 1 bn thm vo thuc tnh AllowSorting="true" khi ny bn s
thy trn dng Header ca Gridview s xut hin nh LinkButton v khi bn nhn vo n, n
cho php bn sp xp thng tin theo th t gim dn v tng dn ca d liu
Kt xut ca chng trnh
Paging Data
Khi s trng d liu ln bn c th thc hin phn trang cho d liu vi vic thit t
thuc tnh AllowPaging="true"
cng vi v d trn bn thm vo thuc tnh AllowPaging,
cho n gi tr bng true v thit lp thuc tnh PageSize(s dng trn mt trang) bng 3 bn
s thy s thay i
Kt xut ca n nh sau:
http://www.ebook.edu.vn
188
PagerSettings-Mode="NextPreviousFirstLast"
Position="TopAndBottom" PagerStyle-HorizontalAlign="Center"
PagerSettings-
AllowPaging="true" DataSourceID="SqlDataSource1"
ID="GridView1" runat="server">
</asp:GridView>
Mode: cho php bn la chn hin th kiu cho giao din phn trang, n c th c cc
gi tr sau:
http://www.ebook.edu.vn
189
http://www.ebook.edu.vn
190
Transitional//EN"
<title>Gridview</title>
<style type="text/css">
.menu td{padding:5px 0px;}
.selectedPage a{font-weight:bold;color:red;}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" AllowPaging="true" PageSize="3"
DataSourceID="SqlDataSource1"
runat="server">
OnDataBound="GridView1_DataBound"
<PagerTemplate>
<table>
<tr>
<td>
<asp:LinkButton id="lnkPrevious" Text="<
CommandArgument="Prev"
ToolTip="Previous
CommandName="Page"
Runat="server" />
Prev"
Page"
</td>
<td>
<asp:Menu
id="menuPager"
Orientation="Horizontal"
OnMenuItemClick="menuPager_MenuItemClick"
StaticSelectedStyleCssClass="selectedPage" CssClass="menu" Runat="server" />
</td>
<td>
CommandName="Page"
/>
<asp:LinkButton
CommandArgument="Next"
</td>
</tr>
</table>
http://www.ebook.edu.vn
191
id="lnkNext"
Text="Next
>"
ToolTip="Next Page" Runat="server"
</PagerTemplate>
</asp:GridView>
<asp:SqlDataSource
ConnectionString="<%$ConnectionStrings:Gridview %>"
SelectCommand="select
runat="server"></asp:SqlDataSource>
ID="SqlDataSource1"
from
tblIntrodure"
</div>
</form>
</body>
</html>
y trong PagerTemple bn thm vo 2 iu khin Linkbutton v 1 iu khin Menu
thc hin phn trang. 2 iu khin Linkbutton vi cc thuc tnh Command v
CommandArgument c GridView h tr ln ta khng phi vit cc phng thc thc thi
cn vi iu menu trong s kin DataBound ca GridView bn cung cp mt phng thc
GridView1_DataBound in d liu cho Menu.
Thay i d liu trong GridView
iu khin GridView ch cho php bn thay i hoc xo d liu trong Database c
in vo n.
V d sau s hng dn bn cch chnh sa d liu v xo d liu trong iu khin
GridView.
V d trang GridviewEdit.aspx
<%@ Page Language="C#" AutoEventWireup="true"
Inherits="_Default" %>
CodeFile="GridviewEdit.aspx.cs"
<!DOCTYPE
html
PUBLIC
"-//W3C//DTD
XHTML
1.0
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>GridView</title>
</head>
<body>
<form id="form1" runat="server">
<div id="navcontain">
<asp:GridView AllowSorting="true" PageSize="10"
http://www.ebook.edu.vn
192
Transitional//EN"
PagerSettings-Mode="NextPreviousFirstLast"
Position="TopAndBottom" PagerStyle-HorizontalAlign="Center"
PagerSettings-
AutoGenerateDeleteButton="true"
AutoGenerateEditButton="true"
DataKeyNames="pkIntrodureID"
AllowPaging="true" DataSourceID="SqlDataSource1"
ID="GridView1" runat="server">
</asp:GridView>
<asp:SqlDataSource
ConnectionString="<%$
ConnectionStrings:Gridview
%>"
SelectCommand="select
pkIntrodureID,sTitle,sSummary,sContent,iPosition from tblIntrodure"
UpdateCommand="Update
tblIntrodure
set
sTitle=@sTitle,
sSummary=@sSummary,
sContent=@sContent,iPosition=@iPosition
where
pkIntrodureID=@pkIntrodureID"
DeleteCommand="Delete
pkIntrodureID=@pkIntrodureID"
from
tblIntrodure
ID="SqlDataSource1" runat="server"></asp:SqlDataSource>
</div>
</form>
</body>
</html>
http://www.ebook.edu.vn
193
where
V d trang GridviewdataNull.aspx
<%@
Page
Language="C#"
AutoEventWireup="true"
CodeFile="GridviewdataNull.aspx.cs" Inherits="_Default" %>
<!DOCTYPE
html
PUBLIC
"-//W3C//DTD
XHTML
1.0
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Transitional//EN"
PagerSettings-
ConnectionString="<%$
%>"
SelectCommand="select * from tblHello"
http://www.ebook.edu.vn
194
ConnectionStrings:Gridview
ID="SqlDataSource1" runat="server"></asp:SqlDataSource>
</div>
</form>
</body>
</html>
I. DetailView
1. Hin th d liu vi DetailView
DetailView c a ra hin th nh mt bng(<Table>) trong HTML hin th d liu
mt bn ghi.
V d: Trang DetailView.aspx
Code 11.1
<%@ Page Language="C#" AutoEventWireup="true"
Inherits="_DetailView" %>
CodeFile="DetailView.aspx.cs"
http://www.ebook.edu.vn
195
<head runat="server">
<title>Detail View</title>
</head>
<body>
<form id="form1" runat="server">
<div id="navcontain">
<asp:DetailsView ID="DetailsView1"
DataSourceID="SqlDataSource1" runat="server" Height="50px"
Width="125px">
</asp:DetailsView>
<asp:SqlDataSource ID="SqlDataSource1"
ConnectionString="<%$ConnectionStrings:hcubiuData %>"
SelectCommand="select * from tblIntrodure"
runat="server"></asp:SqlDataSource>
</div>
</form>
</body>
</html>
Vn vi c s d liu t chng trc bn a d liu ca bng tblIntrodure vo
SqlDataSource v in n vo DetailView1 vi thuc tnh DataSourceID ca n
Kt xut ca chng trnh s nh sau:
http://www.ebook.edu.vn
196
V d:
Bn to mt lp Employee.cs
Code 11.2
using System;
public class Employee
{
private int _PersonID;
public int PersonID
{
get { return _PersonID; }
set { _PersonID = value; }
}
private string _Hoten;
public string Hoten
{
get { return _Hoten; }
set { _Hoten = value; }
}
private int _Tuoi;
public int Tuoi
{
get { return _Tuoi; }
set { _Tuoi = value; }
}
public Employee()
{
}
http://www.ebook.edu.vn
197
http://www.ebook.edu.vn
198
using System.Collections.Generic;
using System.Data;
public partial class DetailViewPerson : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Employee newEmploy=new Employee(1,"HCUBIU",25);
List<Employee> listEmploy=new List<Employee>();
listEmploy.Add(newEmploy);
DetailsView1.DataSource = listEmploy;
DetailsView1.DataBind();
}
}
}
Trong v d ny chng ta to ra mt lp Employee v chng ta a d liu vo
DetailView1 vi thuc tnh DataSource v phng thc DataBind in d liu vo.
2. S dng Fields vi iu khin DetailView
DetailView h tr tt c cc Field nh GridView
CommandField: hin th lin kt cho php chnh sa, thm mi, xo d liu ca
dng.
ImageField: hin th nh
http://www.ebook.edu.vn
199
V d:
Code 11.5
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="DetailViewfield.aspx.cs" Inherits="DetailViewfield" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Fields</title>
</head>
<body>
<form id="form1" runat="server">
<div id="navcontain">
<asp:DetailsView ID="DetailsView1" AutoGenerateRows="false"
DataSourceID="SqlDataSource1" runat="server" Height="50px"
Width="125px">
<Fields>
<asp:BoundField DataField="pkIntrodureID" HeaderText="ID" />
<asp:BoundField DataField="sTitle" HeaderText="Tiu " />
<asp:BoundField DataField="iPosition" HeaderText="V tr" />
</Fields>
</asp:DetailsView>
<asp:SqlDataSource ID="SqlDataSource1"
ConnectionString="<%$ConnectionStrings:hcubiuData %>"
SelectCommand="select * from tblIntrodure"
runat="server"></asp:SqlDataSource>
</div>
</form>
http://www.ebook.edu.vn
200
</body>
</html>
Trong v d trn bn a vo 3 BoundField v in vo d liu vi thuc tnh DataField
v thit t cho n tiu d vi HeaderText, a ra d liu nh th ny bn cn thit lp
thuc tnh AutoGenerateRows=false.
Kt xut ca chng trnh
http://www.ebook.edu.vn
201
bng
V d: DetailViewDatanull.aspx
Code 11.7
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="DetailViewDatanull.aspx.cs" Inherits="DetailViewDatanull" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Null Data</title>
<style type="text/css">
.noMatch{background-color:#ffff66;padding:10px;font-family:Arial,SansSerif;}
.noMatch h1{color:red;font-size:16px;font-weight:bold;}
</style>
</head>
<body>
http://www.ebook.edu.vn
202
http://www.ebook.edu.vn
203
Code 11.8
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="DetailViewPaging.aspx.cs" Inherits="DetailViewPaging" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Paging</title>
</head>
<body>
<form id="form1" runat="server">
<div id="navcontain">
<asp:DetailsView ID="DetailsView1" AllowPaging="true"
DataSourceID="SqlDataSource1" runat="server" Height="50px"
Width="300px">
</asp:DetailsView>
CodeFile="Repeater.aspx.cs"
http://www.ebook.edu.vn
204
<title>Repeater</title>
</head>
<body>
<form id="form1" runat="server">
<div id="navcontain">
<asp:Repeater DataSourceID="SqlDataSource1" ID="Repeater1"
runat="server">
<ItemTemplate>
<div class="navpage">
<h3><%#Eval("sTitle") %></h3>
Tm tt<br /> <%#Eval("sSummary")%><br /><br />
Ni dung<br />
<%#Eval("sContent") %>
</div>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="SqlDataSource1"
ConnectionString="<%$ConnectionStrings:hcubiuData %>"
SelectCommand="select sTitle,sSummary,sContent from tblIntrodure"
runat="server"></asp:SqlDataSource>
</div>
</form>
</body>
</html>
Bn
a
iu
khin
Repeater
vo
Form
v
t
thuc
tnh
DataSourceID=SqlDataSource1 v thm vo mt ItemTemplate trong ny bn c th iu
chnh cch hin th d liu theo mun ca bn vi cc th ca Asp.Net hoc HTML.
Kt xut ca on Code trn s nh sau:
http://www.ebook.edu.vn
205
V d: trang RepeaterDP.aspx
<%@ Page Language="C#" AutoEventWireup="true"
Inherits="_Default" %>
CodeFile="RepeaterDP.aspx.cs"
http://www.ebook.edu.vn
206
http://www.ebook.edu.vn
207
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="SqlDataSource1"
ConnectionString="<%$ConnectionStrings:hcubiuData %>"
SelectCommand="select sTitle,sSummary,sContent from tblIntrodure"
runat="server"></asp:SqlDataSource>
</div>
</form>
</body>
</html>
Kt xut ca chng trnh:
V d trang RepeaterEvent.aspx
http://www.ebook.edu.vn
208
http://www.ebook.edu.vn
209
http://www.ebook.edu.vn
210
<td><%#Eval("sSummary")%></td>
</tr>
<tr>
<td colspan="2">
<asp:LinkButton ID="lbninsert" CommandName="insert"
CommandArgument="insert" runat="server">Insert</asp:LinkButton> |
<asp:LinkButton ID="lbnupdate" CommandName="update"
CommandArgument="update" runat="server">Update</asp:LinkButton> |
<asp:LinkButton ID="lbndelete" CommandName="delete"
CommandArgument="delete" runat="server">Delete</asp:LinkButton>
</td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr class="alternating">
<td><%#Eval("sTitle") %></td>
<td><%#Eval("sSummary") %></td>
</tr>
<tr>
<td colspan="2">
<asp:LinkButton ID="lbninsert" CommandName="insert"
CommandArgument="insert" runat="server">Insert</asp:LinkButton> |
<asp:LinkButton ID="lbnupdate" CommandName="update"
CommandArgument="update" runat="server">Update</asp:LinkButton> |
<asp:LinkButton ID="lbndelete" CommandName="delete"
CommandArgument="delete" runat="server">Delete</asp:LinkButton>
</td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</table>
http://www.ebook.edu.vn
211
</FooterTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="SqlDataSource1"
ConnectionString="<%$ConnectionStrings:hcubiuData %>"
SelectCommand="select sTitle,sSummary,sContent from tblIntrodure"
runat="server"></asp:SqlDataSource>
</div>
</form>
</body>
</html>
V d trn bn a vo 3 s kin cho iu khin Repeater, tng ng vi n l 3 s
kin c kch hot: s kin
Repeater1_ItemDataBound c a ra lm v n c thc hin mi khi d liu hay
mt item c a vo Repeater vi v d trn n s in ra d liu ang c to x(s hng
trong bng d liu) ln.
repeater1_DataBinding
CodeFile="DataList.aspx.cs"
http://www.ebook.edu.vn
212
RepeaterColumns: s ct hin th
V d trang DataListMutilColumn.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="DataListMutilColumn.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Repeater</title>
</head>
<body>
http://www.ebook.edu.vn
213
http://www.ebook.edu.vn
214
V d: trang DataListselect.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="DataListselect.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Repeater</title>
</head>
<body>
<form id="form1" runat="server">
<div id="navcontain">
<asp:DataList ID="DataList1" DataKeyField="pkIntrodureID"
DataSourceID="SqlDataSource1" runat="server">
<ItemTemplate>
<asp:LinkButton ID="lbnselect" CommandName="Select"
runat="server" Text='<%#Eval("sTitle") %>' />
</ItemTemplate>
</asp:DataList>
<asp:DataList ID="datalist2" runat="server"
DataSourceID="SqlDataSource2">
<ItemTemplate>
<h3><%#Eval("sTitle") %></h3>
http://www.ebook.edu.vn
215
http://www.ebook.edu.vn
216
http://www.ebook.edu.vn
217
http://www.ebook.edu.vn
218
Text='<%#Eval("sTitle")
http://www.ebook.edu.vn
219
Form
V d 1: Trang setCookies.aspx
http://www.ebook.edu.vn
220
CodeFile="Default.aspx.cs"
<script runat="server">
protected void Add_Click(object sender, EventArgs e)
{
Response.Cookies["Message"].Value = txtCookies.Text;
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Create Cookies</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Cookie Value"></asp:Label>
<asp:TextBox ID="txtCookies" runat="server"></asp:TextBox>
<asp:Button ID="Add" runat="server" OnClick"Add_Click" Text="Button"
/>
</div>
</form>
</body>
</html>
Trong v d mt l chng ta to ra mt Session Cookies, cn nu bn mun to mt
Persistent Cookies bn cn ch nh thi hn kt thc cho Cookies .
V d 2 trang setPersistentCookies.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="setPersistentCookies.aspx.cs" Inherits="setPersistentCookies" %>
<script runat="server">
http://www.ebook.edu.vn
221
c d liu t Cookies
http://www.ebook.edu.vn
222
http://www.ebook.edu.vn
223
</body>
</html>
Xa Cookies
xa mt Cookie bn thit lp ngy ht hn cho Cookies l -1
V d nh cu lnh di y:
Response.Cookies[Message].Expires = DateTime.Now.AddDays(-1);
Trn v d trn chng ta s xa Cookie vi tn l Message.
V d 4 trang SetCookieValues.aspx
http://www.ebook.edu.vn
224
http://www.ebook.edu.vn
225
<tr>
<td>Mu yu thch</td>
<td><asp:TextBox ID="txtColor" runat="server" /></td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnsubmit" runat="server" Text="Submit"
OnClick="btnsubmit_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Vic ly gi tr ca Cookie nhiu gi tr tng t nh cc phn trn, hc vin v nh
hon thin nt.
http://www.ebook.edu.vn
226
CodeFile="Sessionset.aspx.cs"
2. Ly d liu t mt Session
V d: Trang Sessionset.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Sessionget.aspx.cs"
Inherits="Sessionget" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
lblsession.Text = Session["Message"].ToString();
}
</script>
http://www.ebook.edu.vn
227
http://www.ebook.edu.vn
228
ModeEnables you to determine the current Session state store provider. Possible
TimeoutEnables you to specify the amount of time in minutes before the web
server assumes that the user has left and discards the session. The maximum value
is 525,600 (1 year).
http://www.ebook.edu.vn
229
http://www.ebook.edu.vn
230
Bn to mt Profile bng cch nh ngha mt danh sch cc thuc tnh Profile trong
ng dng file web.config trong th mc root. ASP.NET Framework t ng bin dch mt
lp cha ng cc thuc tnh ny.
V d sau y s a ra mt Profile vi ba thuc tnh: firstName, lastName v
NumberOfVisits:
Trang web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<profile>
<properties>
<add name="firstName" />
<add name="lastName"/>
<add name="NumberOfVisits" type="Int32" defaultValue="0"/>
</properties>
</profile>
</system.web>
</configuration>
Khi lm vic vi Profile bn ch mt s thuc tnh sau:
serializeAs: Enables you to specify how a property is persisted into a static repre-
http://www.ebook.edu.vn
231
Profile.NumberOfVisits++;
numbervisit.Text = Profile.NumberOfVisits.ToString();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
Profile.firstName = txtFirstName.Text;
Profile.lastName = txtLastName.Text;
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>show Profile</title>
</head>
<body>
<form id="form1" runat="server">
<div>
FirstName: <asp:Label ID="firstName" runat="server" /><br />
LastName: <asp:Label ID="lastName" runat="server" /><br />
Number of Visit: <asp:Label ID="numbervisit" runat="server" /><hr />
http://www.ebook.edu.vn
232
http://www.ebook.edu.vn
233
<?xml version="1.0"?>
<configuration>
<system.web>
<profile>
<properties>
<group name="Preferences">
<add name="BackColor" defaultValue="lightblue"/>
<add name="font" defaultValue="Arial"/>
</group>
<group name="ContactInfo">
<add name="Email" defaultValue="hung.le.uh@itechpro.com.vn"/>
<add name="phone" defaultValue="0936302728"/>
</group>
</properties>
</profile>
</system.web>
</configuration>
http://www.ebook.edu.vn
234
pagestyle.Font.Name = Profile.Preferences.font;
Header.StyleSheet.CreateStyleRule(pagestyle, null,"html");
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>show profile group</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Email: <asp:Label ID="lblEmail" runat="server" /><br />
Phone: <asp:Label ID="lblPhone" runat="server" />
</div>
</form>
</body>
</html>
http://www.ebook.edu.vn
235
<configuration>
<system.web>
<authentication mode="Windows" />
<anonymousIdentification enabled="true"/>
<profile>
<properties>
<add name="NumberOfVisits" type="Int32" defaultValue="0"
allowAnonymous="true"/>
</properties>
</profile>
</system.web>
</configuration>
thuc tnh NumberOfVisits bao gm thuc tnh allowAnonymous. Ch rng file
web.config v ch cho php Form Authencation. Khi Form Authentication c cho php v
bn khng login, v khi bn l ngi s dng nc danh.
Trong v d sau s hng dn cch bn sa thuc tnh nh danh khi nh danh nc
danh c cho php.
Trang ShowAnonymousIdentification.aspx;
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="ShowAnonymousIdentification.aspx.cs"
Inherits="ShowAnonymousIdentification" %>
<script runat="server">
void Page_PreRender()
{
lblName.Text = Profile.UserName;
lblanonymous.Text = Profile.IsAnonymous.ToString();
Profile.NumberOfVisits++;
lblnumbetofanonymous.Text = Profile.NumberOfVisits.ToString();
}
protected void btnLogin_Click(object sender, EventArgs e)
{
http://www.ebook.edu.vn
236
FormsAuthentication.SetAuthCookie("Bob", false);
Response.Redirect(Request.Path);
}
protected void btnLogout_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect(Request.Path);
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Show Anonymous Identification</title>
</head>
<body>
<form id="form1" runat="server">
<div>
UseName: <asp:Label ID="lblName" runat="server" /><br />
Is Anonymous: <asp:Label ID="lblanonymous" runat="server" />
Number of Visits: <asp:Label ID="lblnumbetofanonymous" runat="server"
/><br /><hr />
<asp:Button ID="btnReload" Text="Reload" runat="server" />
<asp:Button ID="btnLogin" Text="Login" OnClick="btnLogin_Click"
runat="server" />
<asp:Button ID="btnLogout" Text="Logout" OnClick="btnLogout_Click"
runat="server" />
</div>
</form>
</body>
http://www.ebook.edu.vn
237
</html>
http://www.ebook.edu.vn
238