Professional Documents
Culture Documents
Giao Trinh ASP - Netvoi CSharp
Giao Trinh ASP - 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 3
http://www.ebook.edu.vn
ASP.NET l mt phn ca .NET FrameWork xy dng trang asp.NET bn cn thm vo cc c tnh ca .netframework. NetFrameWork cha ng hai phn FrameWork Class Library v Commom Language Runtime. 1.1 Hiu v Framework Class Library Framework cha ng hng nghn lp m bn c th s dng trong ng dng ca mnh. V d mt vi lp ca .Net Framework -Lp File: cho php bn to file, sa, xo hay kim tra s tn ti ca file trn a cng -Lp Graphics: Cho php bn lm vic vi nhiu kiu ca nh, bn cng c th to ra cc nh t cc phng thc trn lp ny. -Lp SmtpClient: Cho php bn gi th. Hiu v Namespaces: hn 13 nghn lp trong Netframework. y l mt con s rt ln, Microsoft chia cc lp cng x l v mt vn g vo cc khng gian tn chung hay namespaces. Mt Namespace n gin l mt danh mc, v d tt c cc lp thao tc vi File v th mc chng ta a vo mt namespaces chung gi l System.IO, hay tt c cc lp lm vic vi SqlServer c th a vo namespace System.Data.SqlClient. Cc namespaces chung nht trong net: . System . System.Collections . System.Collections.Specialized . System.Configuration . System.Text . System.Text.RegularExpressions . System.Web . System.Web.Caching . System.Web.SessionState . System.Web.Security . System.Web.Profile . System.Web.UI . System.Web.UI.WebControls . System.Web.UI.WebControls.WebParts
http://www.ebook.edu.vn
1.2 Hiu v Assembly: Mt Assembly l mt file dll trn a cng ca bn, ni m lu tr cc lp ca .NET, v d tt c cc lp trong .ASP.NET Framework u nm trong Assembly System.web.dll. Trc khi s dng cc lp trong dll bn cn to mt tham chiu n file dll ny 1.3 Hiu v Commom Language Runtime(CLR) Phn th 2 ca NetFramework l CLR chu trch nhim v thc thi m ng dng ca bn. Khi bn vit ng dng bng ngn ng C#, VB.NET hay bng mt ngn ng bt k trn nn NetFramwork m ca bn s c khng bao gi bin dch trc tip thnh m my. Thay vo chng c bin dng sang ngn ng c t MSIL (Microsoft intermediate Language). MSIL nhn rt ging vi ngn ng hng i tng Assembly, nhng khng ging kiu ngn ng Assembly. MSIL l ngn ng bc thp v ph thuc vo Platform. Khi ng dng ca bn thc thi, m MSIL l just in time bin dch sang m my bi JITTER(just in time compiler) Nh vy khi bn vit cc lp trn .Net bng bt k ngn ng no khi bn bin dch sang Assembly bn u c th s dng Assembly cho cc ngn ng khc. 1.4 Hiu v cc iu khin trn Asp.net Cc iu khin asp.net l phn quan trng nht trong ASP.NET Framework. mt Control ASP.NET l mt lp m thc thi trn server v a ra ni dung trn trnh duyt. ASP.NET c hn 70 control m bn c th s dng trong xy dng ng dng web ca bn v c bn n chia ra cc nhm control sau: Standard control: bao gm cc iu khin a ra cc thnh phn chun ca form nh: Label, Button, TextBox Validator Control: l cc control cho php bn kim tra tnh hp l ca cc control cho php nhp gi tr trn form. Rich Control: l nhng iu khin nh FileUpload, Calendar Data Control l cc iu khin cho php thao tc vi d liu Navigation Control: l nhng iu khin gip bn d dng di chuyn gia cc trang trong website. Login control: L cc iu khin v bo mt ca ng dng cho php bn a ra cc form ng nhp, thay i mt khu HTML Control: cho php bn chuyn cc iu khin ca HTML thnh cc iu khin c th lm vic trn server. 1.5 hiu v iu khin s kin trn server
http://www.ebook.edu.vn
phn ln cc iu khin ca asp.net h tr 1 hoc nhiu s kin, v d iu khin ASP.NET Button h tr s kin Click, khi ngi s dng nhn chut vo Button mt s kin s c a ra v cng vic ny c x l trn server.
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">
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Hiu v s kin pha server</title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" OnClick="Button1_Click" runat="server" Text="Button" /> <hr /> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </div> </form> </body>
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.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Button1_Click(object sender,EventArgs e) { Label1.Text = Convert.ToString(int.Parse(Label1.Text) + 1); } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Under Stand State</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="0"></asp:Label>
http://www.ebook.edu.vn
<asp:Button ID="Button1" OnClick="Button1_Click" runat="server" Text="Button" /> </div> </form> </body> </html> Nu bn m View Source code ca trang Understandstate.aspx trn bn s thy nh
sau:
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE4OTg4OTc0MjUPZBYCAgQPZBYCAgEPDxYCHgRUZXh0BQEzZGRkz0aTZTJffZR UP11aiDXbPGQGitk=" /> <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAgKK7LjKBwKM54rGBgzCWqbCIzq33uVXHF19FzfdGPsJ" /> y l 2 file hidden trong form n cha gi tr Text ca Label khi trang c postback n s ghi nh text v s khi to li gi tr ca Label khi trang Load.
Trang Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.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>Default</title> </head> <body> <form id="form1" runat="server"> <div>
http://www.ebook.edu.vn
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;
public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } }
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# byte char bool sbyte short ushort int uint float
Kiu .Net Byte Char Boolean Sbyte Int16 Int16 Int32 Int32 Single
S Byte 1 2 1 1 2 2 4 4 4
M t s nguyn khng du t 0 n 255 Kiu k t Unicode Gi tr true/false S nguyn c du, t -128 n 127 S nguyn c du t -32768 n 32767 S nguyn khng du t 0 n 65.535 S nguyn c du 2.147.483.647 n 2.147.483.647 S nguyn khng du 0 n 4.294.967.295 kiu du chm ng, gi tr xp x t 3,4E-38 n
http://www.ebook.edu.vn
3,4E+38, vi 7 ch s c ngha. Double Double 8 Kiu du chm ng c chnh xc gp i, gi tr xp x t 1,7E-308 n 1,7E+308, vi 15,16 ch s c ngha Decimal Decimal 8 C chnh xc n 28 con s v gi tr thp phn, c dng trong tnh ton ti chnh, kiu ny i hi phi c hu t m hoc M km theo sau.
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:
http://www.ebook.edu.vn
11
http://www.ebook.edu.vn
12
http://www.ebook.edu.vn
13
} }
h, S dng trnh by return(c s dng trong cc hm tr v gi tr c th cho hm) V d public int sum(int a, int b) { return a + b; }
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.
<!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>Basic</title> </head> <body> <form id="form1" runat="server"> <div> <% string abc = "Hello World!"; %> Bin abc ca bn va khai bo c gi tr <%=abc %>
http://www.ebook.edu.vn
15
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" %>
<!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>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <h3>Gn gi tr:</h3> <asp:Label ID="lblhello" runat="server" Text="Label"></asp:Label><br /><br /> <h3>Ly gi tr t code behind</h3> <%=_hello %> </div> </form>
http://www.ebook.edu.vn
16
</body>
http://www.ebook.edu.vn
17
ti y chng ta c th vit vo cc lp th vin. to mt lp th vin trong th mc ny chng ta nhn chut phi vo th mc App_code ri chn Add New Item
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
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
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UseHelloworld.aspx.cs" Inherits="UseHelloworld" %> <!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 Hello World trong th mc App_Code</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lblHello" runat="server" Text="Label"></asp:Label> </div> </form> </body> </html> Trang UseHelloworld.aspx.cs using System; public partial class UseHelloworld : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lblHello.Text = HelloWorld.sayMessage(); } } V phng thc sayMessage trong lp HelloWorld l mt phng thc tnh ln ta khng cn khi to lp s dng.
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
Xy dng lp: Construction.cs using System; public class Construction { int _giatri1; int _giatri2; public Construction() { _giatri1 = 0; _giatri2 = 0; } public Construction(int _giatri1, int _giatri2) { this._giatri1 = _giatri1; this._giatri2 = _giatri2; } public int Sum() { return _giatri1 + _giatri2; } } Trong lp ny chng ta xy dng hai phng thc khi dng mt phng thc khng c i s v mt phng thc c i s, v mt hm tnh tng ca 2 gi tr n c s dng trang trang asp.net nh sau: Trang UseConstruction.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="UseConstruction.aspx.cs" Inherits="UseConstruction" %> <!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
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
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <h1>Chng ho phng thc tnh tng</h1> Tng 2 s:<asp:Label ID="lbl2so" runat="server" Text="Label"></asp:Label><br /><br /> Tng 3 s:<asp:Label ID="lbl3so" runat="server" Text="Label"></asp:Label><br /><br /> Tng 4 s:<asp:Label ID="lbl4so" runat="server" Text="Label"></asp:Label><br /><br /> </div> </form> </body> </html> Trang Overloading.aspx.cs using System;
public partial class Overloading : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lbl2so.Text = UseOverload.Sum(5, 5).ToString(); lbl3so.Text = UseOverload.Sum(5, 5, 5).ToString(); lbl4so.Text = UseOverload.Sum(5, 5, 5, 5).ToString(); }
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:
5.4 Khai bo khng gian tn (Namespaces) Nu bn tng lp trnh java chc hn bn quen vi khi nim packed m bn ng gi cc lp m bn xy dng c c tnh chung(miu t hay x l vn g ). Trong .Net cng vy t kho Namespaces cng c nhim v nh packed trong java. .Net cung cp cho chng ta cc Namespaces nh: using System.Configuration; 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; V s dng cc Namespaces trong C# bn cn s dng t kho using. Mt Namespaces c th cha cc Namespaces con, v trong Namespace con nht cha cc lp thnh vin V d Bn to ra hai lp php cng v php tr thc hin cc php ton tng ng nh sau: Lp Phepcong.cs using System; namespace iTechPro.Tinhtoan { public class Phepcong
http://www.ebook.edu.vn
27
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
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <h1>Khai bo v s dng Namespaces</h1> Lp php cng: <asp:Label ID="lblcong" runat="server" Text="Label"></asp:Label><br /><br /> Lp php tr: <asp:Label ID="lbltru" runat="server" Text="Label"></asp:Label> </div> </form> </body> </html> Lp Namespaces.aspx.cs using System; using iTechPro.Tinhtoan; public partial class Namespaces : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lblcong.Text = Phepcong.Sum(5, 5).ToString(); lbltru.Text = Pheptru.Minus(5, 5).ToString(); } }
http://www.ebook.edu.vn
29
Nh v d trn bn thy chng ta s dng namespace iTechPro.Tinhtoan ging vi cc Namespace khc m Microsoft cung cp cho chng ta. Kt xut ca chng trnh
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;} } }
Trong v d trn Lp OnSaleProduct c k tha t lp ProductBase v Override thuc tnh Price, lp ny mun ch ra gi bng mt na lp c s. ch vi VB.NET th t kho base l MyBase. Bn c th dng t kho abstract khi khai bo mt lp nh nh du lp ny yu cu k tha. Bn khng th to i tng mt lp tru tng, s dng mt lp tru tng bn phi dn xut mt lp mi t lp tru tng v to i tng trong lp dn xut. V d:
http://www.ebook.edu.vn
34
public string Company { get { return "iTechPro"; } } } public class SaleEmployee:BaseEmployee { public override decimal Salary { get { return 66.666; } } } Trong v d trn bn thy Lp SaleEmployee c k tha t lp BaseEmployee v Overload thuc tnh Salary.
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
nh hng Cho php thay i mu nn ca Label Cho php thit lp ng vin ca Label Hin th ng vin ca Label theo cc dng Notset, None, Dotted, Dashed, Solid, Double, Groove, Ridge, Insert v OutSet.
Cho php a vo mt lp css Thit lp thuc tnh ca Font Thit t mu ch ni dung ca Label Cho php gn cc thuc tnh cho Label Hin th ni dung khi di chut vo iu khin Label 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
Kiu hin th ca Textbox gm 3 gi tr: SingleLine- hin th 1 trng nhp liu trn 1 dng, MultiLine- hin th 1 trng nhp liu nhiu dng, Password- hin th 1 trng nhp m Text s c thay th bng cc k t c bit
AccessKey
AutoCompleteType
AutoPostBack
Cho php ch nh s ct c hin th trong TextBox Cho php hay khng cho php nhp liu trn TextBox Cho php quy inh di ca d liu m mt ngi s dng c th nhp trn TextBox
ReadOnly
Cho php ch nh s dng hin th trong TextBox Cho php ch nh th t Tab ca TextBox Cho php ch nh c word-wraps khng khi thit lp thuc tnh TextMode l Multiline
iu khin TextBox h tr phng thc v s kin sau: - Focus: cho php thit lp form khi to u tin ti TextBox - TextChanged: Xy ra trn Server khi ni dung TextBox thay i. s kin ny xy ra bn cn thit t thuc tnh AutoPostback l true. 2. S dng iu khin CheckBox Cc thuc tnh AccessKey Enables you to specify a key that navigates to the TextBox contro AutoPostBack nablesyou to post the form containing the CheckBox back to the
http://www.ebook.edu.vn
39
server automatically when the CheckBox is checked or unchecked Checked Cho php bn gn hoc thit t trng thi chn hay khng chn ca CheckBox Enabled TabIndex Text TextAlign Cho php hoc khng cho php Enables you to specify the tab order of the check box. Enablesyou to provide a label for the check box. Enables you to align the label for the check box. Possible values are Left and Right.
CheckBox h tr phng thc va s kin - Focus: Enables you to set the initial form focus to the check box. - CheckedChanged: Raisedontheserverwhenthecheckboxischeckedorunchecked. 3. iu khin RadioButton iu khin RadioButton lun c s dng trong mt nhm v trong nhm ch mt RadioButton c chn Cc thuc tnh Thuc tinh AccessKey Enablesyou to specify a key that navigates to the RadioButton control AutoPostBack Enables you to post the form containing the RadioButton back to the server automatically when the radio button is checked or unchecked Checked Enables you to get or set whether the RadioButton control is checked. Enabled GroupName Enables you to disable the RadioButton Enables you to group RadioButton controls
http://www.ebook.edu.vn
40
Enables you to specify the tab order of the RadioButton control. Enables you to label the RadioButton control. Enablesyou to align the RadioButton label. Possible values are Left and Right.
RadioButton h tr cc phng thc v s kin - Focus: Enables youto set the initial form focus to the RadionButton control. - CheckedChanged: Raised on the server when the unchecked.
Cho php ch nh phm di chuyn ti iu khin Button. Cho php bn ch r i s c truyn ti lnh thc hin. Ch nh tn mt lnh c truyn ti trong Command Event. Cho php v hiu ho iu khin Button Cho php ch nh n mt hm pha client khi nhn vo Button. Cho php tr d liu ln mt trang khc. Ch nh th t tab ca Button. Ni dung text hin th trn iu khin Button. Cho php s dng javascript tr d liu ln mt form.
Cc phng thc v s kin - Focus: Cho php thit lp khi khi to Form u tin iu khin TextBox. - Click: Xy ra khi iu khin Button c nhn.
http://www.ebook.edu.vn
41
- Command: Xy ra khi iu khin Button c nhn. CommandName v CommandArgument c truyn qua s kin. 2. iu khin LinkButton: cc phng thc v thuc tnh ging vi iu khin Button nhng cch hin th ca n di dng Text ging nh th <a> ca HTML v c th p dng thuc tnh css ca th <a> cho i tng LinkButton. Hc vin t tm hiu thm 3. iu khin ImageButton Cc thuc tnh v phng thc ca iu khin Button v thm vo mt s thuc tnh
Thuc tnh ImageUrl ImageAlign Ch n ng dn ca nh Cho php cn chnh nh trong ImageButton cc gi tr ca n c th l: AbsBottom, AbsMiddle, Baseline, Bottom, Left, Middle, NotSet, Right, TextTop, and Top.
4. S dng Client Scripts vi iu khin Button C ba iu khin Button trn u c thuc tnh OnClientClick, bn c th s dng thuc tnh ny thc hin m pha Client m bn cn khi iu khin Button c nhn.
<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>
Trong thuc tnh PostBackUrl ca iu khin btnSearch s chuyn sang trang ButtonSearchResult <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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>
Trong on m trn ta phng thc FindControl ca PreviousPage n s tm n iu khin trn trang ButtonSearch.aspx m ta cung cp ID ca n.
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.
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>
C ba iu khin Button trn u cha Tn lnh v i s lnh v tu thuc vo i s lnh khc nhau ta c th thc hin mt cng vic tng ng.
IV. iu khin hin th nh ASPNET bao gm 2 iu khin hin th nh. iu khin Image v ImageMap. 1. iu khin Image. iu khin ny dng hin th nh ging vi th <Img> trong HTML Cc thuc tnh quan tm Thuc tnh
http://www.ebook.edu.vn
48
AlternateText DescriptionUrl
Ni dung thay th khi li ng dn ca nh Cho php bn cung cp mt ng dn n trang miu t chi tit ni dung ca nh
ImageAlign
Cho php cn chnh nh ln quan ti cc thnh phn HTML khc trong trang v n c th l cc gi tr sau:AbsBottom, AbsMiddle, Baseline, Bottom, Left, Middle, NotSet, Right, TextTop, and Top.
ImageUrl V d
ng dn ca nh trn iu khin
<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
<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#"%>
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
- 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++) { buletnghenghiep.Items.Add("Ngh "+i.ToString()); } }
http://www.ebook.edu.vn
53
void hcubiuSothich(object sender, EventArgs e) { if (chkhtsothich.Checked == true) panelsothich.Visible = true; else panelsothich.Visible = false; }
void hcubiuNghenghiep(object sender, EventArgs e) { if (chkhtnghenghiep.Checked == true) panelnghenghiep.Visible = true; else panelnghenghiep.Visible = false; } </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: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
nh hng Cho php thay i mu nn ca Label Cho php thit lp ng vin ca Label Hin th ng vin ca Label theo cc dng Notset, None, Dotted, Dashed, Solid, Double, Groove, Ridge, Insert v OutSet.
Cho php a vo mt lp css Thit lp thuc tnh ca Font Thit t mu ch ni dung ca Label Cho php gn cc thuc tnh cho Label Hin th ni dung khi di chut vo iu khin Label 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:
http://www.ebook.edu.vn
58
- Focus: cho php thit lp form khi to u tin ti TextBox - TextChanged: Xy ra trn Server khi ni dung TextBox thay i. s kin ny xy ra bn cn thit t thuc tnh AutoPostback l true. 2. S dng iu khin CheckBox Cc thuc tnh AccessKey Enables you to specify a key that navigates to the TextBox contro AutoPostBack nablesyou to post the form containing the CheckBox back to the server automatically when the CheckBox is checked or unchecked Checked Cho php bn gn hoc thit t trng thi chn hay khng chn ca CheckBox Enabled TabIndex Text TextAlign Cho php hoc khng cho php Enables you to specify the tab order of the check box. Enablesyou to provide a label for the check box. Enables you to align the label for the check box. Possible values are Left and Right.
CheckBox h tr phng thc va s kin - Focus: Enables you to set the initial form focus to the check box. - CheckedChanged: Raisedontheserverwhenthecheckboxischeckedorunchecked. 3. iu khin RadioButton iu khin RadioButton lun c s dng trong mt nhm v trong nhm ch mt RadioButton c chn Cc thuc tnh Thuc tinh
http://www.ebook.edu.vn
59
AccessKey
AutoPostBack
Enables you to post the form containing the RadioButton back to the server automatically when the radio button is checked or unchecked
Checked
Enables you to disable the RadioButton Enables you to group RadioButton controls Enables you to specify the tab order of the RadioButton control. Enables you to label the RadioButton control. Enablesyou to align the RadioButton label. Possible values are Left and Right.
RadioButton h tr cc phng thc v s kin - Focus: Enables youto set the initial form focus to the RadionButton control. - CheckedChanged: Raised on the server when the unchecked.
Cho php ch nh phm di chuyn ti iu khin Button. Cho php bn ch r i s c truyn ti lnh thc hin. Ch nh tn mt lnh c truyn ti trong Command Event. Cho php v hiu ho iu khin Button Cho php ch nh n mt hm pha client khi nhn vo Button. Cho php tr d liu ln mt trang khc.
http://www.ebook.edu.vn
60
Ch nh th t tab ca Button. Ni dung text hin th trn iu khin Button. Cho php s dng javascript tr d liu ln mt form.
Cc phng thc v s kin - Focus: Cho php thit lp khi khi to Form u tin iu khin TextBox. - Click: Xy ra khi iu khin Button c nhn. - Command: Xy ra khi iu khin Button c nhn. CommandName v CommandArgument c truyn qua s kin. 2. iu khin LinkButton: cc phng thc v thuc tnh ging vi iu khin Button nhng cch hin th ca n di dng Text ging nh th <a> ca HTML v c th p dng thuc tnh css ca th <a> cho i tng LinkButton. Hc vin t tm hiu thm 3. iu khin ImageButton Cc thuc tnh v phng thc ca iu khin Button v thm vo mt s thuc tnh
Thuc tnh ImageUrl ImageAlign Ch n ng dn ca nh Cho php cn chnh nh trong ImageButton cc gi tr ca n c th l: AbsBottom, AbsMiddle, Baseline, Bottom, Left, Middle, NotSet, Right, TextTop, and Top.
4. S dng Client Scripts vi iu khin Button C ba iu khin Button trn u c thuc tnh OnClientClick, bn c th s dng thuc tnh ny thc hin m pha Client m bn cn khi iu khin Button c nhn.
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
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#" %>
<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>
Trong thuc tnh PostBackUrl ca iu khin btnSearch s chuyn sang trang ButtonSearchResult <%@ Page Language="C#" %> <!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
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>
Trong on m trn ta phng thc FindControl ca PreviousPage n s tm n iu khin trn trang ButtonSearch.aspx m ta cung cp ID ca n.
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
7. iu khin Command Event 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";
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>
C ba iu khin Button trn u cha Tn lnh v i s lnh v tu thuc vo i s lnh khc nhau ta c th thc hin mt cng vic tng ng.
http://www.ebook.edu.vn
67
IV. iu khin hin th nh ASPNET bao gm 2 iu khin hin th nh. iu khin Image v ImageMap. 1. iu khin Image. iu khin ny dng hin th nh ging vi th <Img> trong HTML Cc thuc tnh quan tm Thuc tnh AlternateText DescriptionUrl Ni dung thay th khi li ng dn ca nh Cho php bn cung cp mt ng dn n trang miu t chi tit ni dung ca nh ImageAlign Cho php cn chnh nh ln quan ti cc thnh phn HTML khc trong trang v n c th l cc gi tr sau:AbsBottom, AbsMiddle, Baseline, Bottom, Left, Middle, NotSet, Right, TextTop, and Top. ImageUrl V d <%@ Page Language="C#" %> ng dn ca nh trn iu khin
<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
Image1.AlternateText = "Picture 2"; break; case 2: Image1.ImageUrl = "Images/images3.jpg"; Image1.AlternateText = "Picture 3"; 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: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()); } }
void hcubiuSothich(object sender, EventArgs e) { if (chkhtsothich.Checked == true) panelsothich.Visible = true; else panelsothich.Visible = false; }
void hcubiuNghenghiep(object sender, EventArgs e) { if (chkhtnghenghiep.Checked == true) panelnghenghiep.Visible = true; else panelnghenghiep.Visible = false; } </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
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
http://www.ebook.edu.vn
75
CustomValidator: Bn c th tu chnh i tng Validator theo ca mnh ValidationSummary: cho php hin th tng hp tt c cc li trn 1 trang.
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: ControlToValidate: ch n iu khin cn kim tra Text(ErrorMessage): Ni dung thng bo li MinimumValue: Gi tr nh nht thit lp cho i tng MaximumValue: Gi tr ln nht thit lp cho i tng Type: Kiu so snh, C th l cc gi tr Interger,String, Double, Date v Currency.
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
S dng kim tra kiu d liu S dng so snh gi tr nhp vi mt gi tr c nh S dng so snh gia tr nhp vi gi tr ca mt iu khin khc trn Form
2. Cch s dng
Bn a iu khin CompareValidator vo Form v thit lp cho n mt s thuc tnh sau: ControlToValidate: iu khin ca Form s c kim tra ControlToCompare: iu khin dng so snh gi tr Text(ErrorMessage): hin th ni dung thng bo li kho c li Type: Kiu ca gi tr s c so snh Operator: Ton t so snh. C th l cc gi tr: DataTypeCheck, Equal, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, NotEqual.
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.
Code 4: Trang CompareValidator.aspx <%@ 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> </head> <body> <form id="form1" runat="server"> <div>
http://www.ebook.edu.vn
82
<asp:Label ID="Label1" runat="server" Text="Ngy sinh"></asp:Label> <asp:TextBox ID="txtNgaysinh" runat="server" Width="154px"></asp:TextBox> <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="txtNgaysinh" ErrorMessage="Sai d liu phi l kiu ngy thng" Operator="DataTypeCheck" Type="Date"></asp:CompareValidator> <br /> <asp:Button ID="Button1" runat="server" Text="Accept" />
V d sau y s hng a ra trng hp vi Form to ti khon trn mt trn Web yu cu ngi ng k phi nhp mt khu 2 ln.
http://www.ebook.edu.vn
83
<asp:Label ID="Label2" runat="server" Text="Nhp mt khu "></asp:Label> <asp:TextBox ID="txtPass" runat="server" TextMode="Password"></asp:TextBox> <br /> <asp:Label ID="Label3" runat="server" Text="Nhp li mt khu"></asp:Label> <asp:TextBox ID="txtrePass" runat="server" TextMode="Password"></asp:TextBox> <asp:CompareValidator ID="CompareValidator2" runat="server" ControlToCompare="txtPass" ControlToValidate="txtrePass" ErrorMessage="Nhp mt khu 2 ln phi ging nhau"></asp:CompareValidator> <br /> <asp:Button ID="Button2" runat="server" Text="Accept" />
V. iu khin CustomValidator
1.
ngha
http://www.ebook.edu.vn
84
Nu nhng iu khin Validator trn cha vi bn hoc bn mun to mt Validator ring theo mnh, bn c th dng iu khin CustomValidator, bn c th kt hp CustomValidator vi mt hm.
2. Cch s dng v V d
CustomValidator c 3 thuc tnh hay s dng l: ControlToValidator: iu khin ca Form s c kim tra Text(ErrorMessage): hin th ni dung thng bo li kho c li ClientValidationFunction: tn ca mt hm client-side thc hin kim tra trn client-side 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.
<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>
<asp:Label ID="Label1" runat="server" Text="Ghi ch"></asp:Label> <br /> <asp:TextBox ID="TextBox1" runat="server" Height="95px" TextMode="MultiLine" Width="218px"></asp:TextBox> <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage=" di ghi ch phi nh hn 20 k t" ControlToValidate="TextBox1" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator> <br /> <asp:Button ID="Button1" runat="server" Text="Accept" />
v d 6 trong hm CustomValidator1_ServerValidate Tham s th 2 c truyn ti s kin ServerValidator x l. Trong thc th ca lp ServerValidateEventArgs c hai thuc tnh Value: Gi tr ca trng trn Form s c kim chng.
http://www.ebook.edu.vn
86
IsValid: Din t vic kim chng cho kt qu thnh cng hoc sai.
Trong v d tip theo ti s a ra cch s dng hm kim chng Client-side kt hp vi CustomValidator nh th no, Trang ny ch kim tra di ca chui nhp vo bn trong TextBox, nhng n s kim tra trn c Server v Client.
<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
<asp:Label ID="Label1" runat="server" Text="Ghi ch"></asp:Label> <br /> <asp:TextBox ID="TextBox1" runat="server" Height="95px" TextMode="MultiLine" Width="218px"></asp:TextBox> <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage=" di ghi ch phi nh hn 20 k t" ClientValidationFunction="valComments_ClientValidate" ControlToValidate="TextBox1" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator> <br /> <asp:Button ID="Button1" runat="server" Text="Accept" />
1. ngha
http://www.ebook.edu.vn
88
ValidationSummary cho php bn lit k tt c cc cc li kim tra trn trang t nhng iu khin validator vo mt v tr. iu khin ny c bit tin ch vi Form c rng ln.
2. cch s dng
Bn a iu khin ValidationSummary vo Form v thit lp cho n mt s thuc tnh DisplayMode: Cho php bn ch r nh dng hin th li, n c th l cc gi tr nh BulletList, List, v SingleParagraph. HeaderText: Cho php bn hin th tiu tm tt cho cc li. ShowMessageBox: Cho hin th mt popup thng bo ShowSummary: Cho php bn n ValidationSummary trn trang.
sau:
3. v d
</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"
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:
Cng vi v d trn nu trn iu khin ValSummary ta thit lp thuc tnh ShowMessageBox bng True v ShowSummary vi gi tr bng False th kt xut ca v d thay v hin th l mt danh sch li trn Form th n hin th mt popup thng bo nhng li trn trang.
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"
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"
http://www.ebook.edu.vn
92
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"> <asp:Button ID="Button1" runat="server" Text="Accept" /> </td> </tr> </table>
Kt xut ca n:
http://www.ebook.edu.vn
93
VII. To cc iu khin kim tra tnh hp l theo mnh. Trong phn ny bn s hc to cc iu khin tu bin nh th no. Chng ta s to iu khin. u tin s to mt iu khin kim tra di ca mt trng nhp liu trn Form LengthValidator, Bn to mi mt Control Kim tra tnh hp l bng cch dn xut t lp BaseValidator. Lp BaseValidator l lp c s cho tt c cc iu khin Validation, bao gm RequiredFieldValidator v RegularExpressionValidator Lp c s l lp 1 lp phi c ci t m yu cu bn ci t mt phng thc n.
Khi bn to mt iu khin kim tra tnh hp l tu bin, bn override phng thc EvaluateIsValid() v trong phng thc ny bn gi GetControlValidationValue ly gi tr ca trng cn kim tra tnh hp l. To mt iu khin LengthValidator. Trong phn ny bn s c hc cch to mt iu khin n gin kim tra di ca trng nhp liu. Di y m m ngun ca lp LengthValidator.cs
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
public int MaximumLength { get { return _maximumLength; } set { _maximumLength = value; } } protected override bool EvaluateIsValid() { String value = this.GetControlValidationValue(this.ControlToValidate); if (value.Length > _maximumLength) return false; else return true; } } }
Trong Lp on m trn ta thy LengthValidator c k tha t lp BaseValidator, trong lp mi ny ghi phng thc EvaluateIsValid. Gi tr ca iu khin c kim chng c ly v vi phng thc GetControlValidationValue V di ca gi tr s c so snh vi thuc tnh MaximumLength. s dng iu khin LenghtValidator chng ta phi ng k iu khin ny u trang vi th ch dn <%@ Register %>. nu bn mun s dng LengthValidator cho nhiu trang bn c th ng k iu khin ny phn <Page> trong file Web configuration. V d s dng LengthValidator
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>
Ch dn <%@ Register %>, Vi tin t TagPrefix=Validator v Ch n Namespace=MyControls v s dng iu khin ny ging vi cc iu khin Validator khc.
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 Enable FileBytes FileContent FileName HasFile PostedFile ngha Cho php bn v hiu ho iu khin FileUpload. Cho php ly ni dung file c upload nh mt mng Byte. Cho php ly ni dung ca file c upload theo dng d liu Ly tn file c Upload Tr v gi tr ng khi File c Upload Enables you to get the uploaded file wrapped in the HttpPostedFile object.
iu khin FileUpload h tr cc phng thc Focus: Enables you to shift the form focus to the FileUpload control. SaveAs: Cho php bn lu file c upload ln h thng.
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: ContentLength: Ly v kch thc ca File Upload tnh theo byte ContentType: ly kiu MIME ca File Upload FileName: cho php ly tn ca file c upload. InputStream: Enables you to retrieve the uploaded file as a stream. Lp HttpPostedFile ch h tr phng thc SaveAs: Cho php bn lu file c upload ln h thng.
Upload 1 file ln server Trong v d sau bn s c hc cch Upload 1 file nh ln a cng ca Server.
http://www.ebook.edu.vn
97
<!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>FileUpload</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="Chn File"></asp:Label> <asp:FileUpload ID="FileUpload1" runat="server" Width="286px" /> <br /> <asp:Button ID="Button1" runat="server" Text="Add image" Width="92px" onclick="Button1_Click" /> <hr /> <br /> <asp:DataList ID="listImage" RepeatColumns="3" runat="server"> <ItemTemplate> <asp:Image ID="Image1" ImageUrl='<%# Eval("Name", "~/Upload/{0}") %>' style="width:200px" Runat="server" /> <br /> <%# Eval("Name") %> </ItemTemplate> </asp:DataList> </div>
http://www.ebook.edu.vn
98
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.
II. iu khin Calendar Bn c th hin th mt lch trn trang web ca mnh vi iu khin Calendar V d sau s trnh by mt Calendar n gin
<%@ Page Language="C#"%> <!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>Calendar</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Calendar ID="Calendar1" runat="server"></asp:Calendar> </div> </form> </body> </html> Kt xut ca n s nh sau:
Cc thuc tnh:
Thuc tnh DayNameFormat ngha Cho php bn ch r s xut hin cc ngy ca tun, c th l cc gi tr: FirstLetter, FirstTwoLetters, Full, Short, v Shortest.
NextMonthText
http://www.ebook.edu.vn
101
NextPrevFormat
Cho php bn ch r nh dng thng tip theo v thng trc , n c th l cc gi tr: CustomText, FullMonth, v ShortMonth.
Cho php bn ch nh hin th text cho lin k thng trc Cho php bn ly v hoc thit t cho ngy la chn Cho php bn gn hoc ly v mt tp cc ngy c la chn Cho php ch nh cc ngy c la chn c gi tr nh th no, n c th l cc gi tr sau: Day, DayWeek, DayWeekMonth, v none.
Cho php hin th Text cho 1 thng c chn Cho php hin th Text cho 1 tun c chn Cho php hin th tn ngy hay khng trn nh ca iu khin. Cho php hin th hay khng lin kt n thng tip theo hoc thng trc .
ShowTitle
Cho php bn n hay hin Text trn thanh tiu ca iu khin Calendar.
TitleFormat
TodaysDate
Cc S kin.
DayRender: Raised as each day is rendered. SelectionChanged: Xy ra khi mt ngy mi, tun mi hay thng mi c la chn. VisibleMonthChanged: xy ra khi lin kt n thng tip theo hoc thng trc c nhn. 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
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Multi select date</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Calendar ID="calendar1" SelectionMode="DayWeekMonth" runat="server" SelectedDate="2008-04-18" TitleFormat="Month"></asp:Calendar> <br /> <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" Width="83px" /><br /> <hr /> </div> <asp:BulletedList ID="bllresult" runat="server" DataTextFormatString="{0:d}"> </asp:BulletedList> </form> </body> </html>
http://www.ebook.edu.vn
103
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">
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Pop-up Date Picker</title> <script type="text/javascript">
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
<form id="form1" runat="server"> <div class="content"> <asp:Label id="lblEventDate" Text="Nhp ngy:" Runat="server" /> <asp:TextBox id="txtEventDate" Runat="server" /> <img src="img.gif" alt="" onclick="displayCalendar()" /> <div id="datePicker"> <asp:Calendar id="calEventDate" OnSelectionChanged="calEventDate_SelectionChanged" Runat="server" /> </div> <br /> <asp:Button id="btnSubmit" Text="Submit" Runat="server" OnClick="btnSubmit_Click" /> <hr /> <asp:Label id="lblResult" runat="server" /> </div> </form> </body> </html> III. iu khin Advertisements(Trnh by qung co - Adrotator) Cho php bn hin th cc nh qung co khc nhau trong 1 trang. bn c th lu tr cc qung co ca bn trong 1 file XML hoc mt bng c s d liu. . Cc thuc tnh Thuc tnh AdvertisementFile ngha Cho php bn ch nh n ng dn file XML cha ng danh sch nh qung co AlternateTextField Cho php ch nh n tn ca trng hin th ni dung thay th khi nh qung co v mt l do no khng hin th c DataMenber Cho php rng buc n mt thnh vin c s d liu ca ngun c s d liu DataSource Ch r c s d liu cha danh sch cc banner qung co
http://www.ebook.edu.vn
107
Rng buc n 1 c s d liu Ch r n trng cha ng dn banner qung co Cho php bn lc qung co bi 1 t kho Ch r n tn ca trng cha cc lin kt qung co Cho php bn m ra mt ca s mi khi nhn vo banner qung co
S kin AdCreated: Xy ra sau khi iu khin Adrotator la chn mt qung co nhng trc khi iu khin AdRotator a ra qung co.
Ch rng iu khin AdRotator cha ng thuc tnh KeywordFilter bn c th cung cp mi banner qung co vi 1 t kho sau khi trnh by qung co chng ta c th lc nhng qung co theo iu kin hin th. V d nh trn trang ca bn, bn cn trnh by qung co 4 v tr trn banner(top) ca trang, bn trai, phi v pha chn(bottom) ca trang. Khi bn gn vi mi nh qung co mt t kho(v d tng ng vi 1- top, 2- right, 3 bottom, 4 - left) v khi trnh by trong iu khin AdRotator ta c th dng thuc tnh KeywordFilter lc v trnh by. V d 1: Trn trang web ca bn trnh by qung co hai v tr(trn u v bn phi ca trang) layout nh sau
http://www.ebook.edu.vn
108
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>AdRotator XML</title> <style type="text/css"> #wrapper {width: 782px; margin: 0 auto;} #border { border: 1px solid #8ECE5F; margin: 20px 0px 5px 0px; background-color: #ffffff; min-height: 776px; float: right; width: 780px;} #header {background-color:#BECEF5; text-align: width:782px; height:100px; center; margin: 6px 0px 0px 0px;} #right{background-color:#BECEF5; width:170px;margin: 6px 0px 0px 4px; height:300px; float:right} .box{ float:right;padding:10px; border-left:solid 1px black;} </style> </head> <body> <form id="form1" runat="server"> <div id="wrapper" > <div id="border"> <div id="header"> <asp:AdRotator ID="advbanner" AdvertisementFile="~/App_Data/AdList.xml" KeywordFilter="banner" runat="server" /> </div>
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. ActiveViewIndex: La chn iu khin View c a ra hin th bng ch s Index Views: Cho php bn ly v tp hp cc iu khin View cha ng trong iu khin MultiView.
http://www.ebook.edu.vn
113
iu khin MultiView h tr hai phng thc. GetActiveView: Cho php ly v thng tin ca iu khin View c la chn. SetActiveView: cho php bn thit lp iu khin View c hin th. V MultiView h tr s kin sau: ActiveViewChanged: Xy ra khi iu khin View c la chn
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
<asp:View ID="view2" runat="server"> Day la View 2<br /> Day la View 2<br /> Day la View 2<br /> Day la View 2<br /> Day la View 2<br /> Day la View 2<br /> </asp:View> <asp:View ID="view3" runat="server"> Day la View 3<br /> Day la View 3<br /> Day la View 3<br /> Day la View 3<br /> Day la View 3<br /> Day la View 3<br /> </asp:View> </asp:MultiView> </div> </div> </form> </body> </html> Trong v d trn Menu c kt hp vi CSS to ra cc trng thi khi MenuItem c chn(StaticSelectedStyle-CssClass="selectedTab") v ko c chn(StaticMenuItemStyle-CssClass="tab").
http://www.ebook.edu.vn
117
NextView: MultiView s kch hot iu khin View tip theo PrevView: MultiView s kch hot iu khin View trc SwitchViewByID: MultiView s kch hot View ch nh bi i s ca iu khin Button
Bn c th s dng cc iu khin lnh nh Button, ImageButton, LinkButton. V thit lp thuc tnh CommandName, vi trng hp iu khin lnh l SwitchViewByID v SwitchViewByIndex bn thit lp thm thuc tnh CommandArgument. V d sau s hng dn bn to mt Form c nhiu phn vi vic s dng iu khin lnh NextView.
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">
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>MultiPart View</title> </head> <body> <form id="form1" runat="server">
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.
iu khin Wizard ging vi iu khin MultiView c th dng chia mt Form ln thnh nhiu phn nh. Tuy nhin n s c thm mt s thuc tnh m MultiView khng h tr. iu khin Wizard c th cha nhiu iu khin WizardStep con, nhng ch 1 WirardStep c hin th ti 1 thi im.
Cc thuc tnh.
ActiveStep: cho php bn ly thng tin ca WizardStep ang kch hot ActiveStepIndex: cho php bn gn hoc ly v ch s Index ca WizardStep ang kch hot CancelDestinationPageUrl: cho php bn ch r a ch URL c gi ti khi ngi s dng nhn nt Cancel DisplayCancelButton: Cho php n hoc hin Cancel Button. DisplaySlideBar: Cho php n hoc hin SlideBar(hin th tt c cc WizardStep) FinishDestinationPageUrl: cho php bn ch nh a ch URL c gi ti khi ngi dng nhn nt Finish HeaderText: cho php bn ch nh tiu hin th trn nh ca iu khin Wizard. WizadSteps: Cho php bn ly thng tin ca cc iu khin WizardStep trong iu khin Wizard iu khin Wizard h tr cc Template. FinishNavigationTemplate: cho php hin th Navigation bc kt thc HeaderTemplate: hin th thanh tiu u ca iu khin Wizard SlideBarTemplate: Cho php hin th SlideBar trong iu khin Wizard StartNavigationTemplate: Cho php hin th Navigation bc bt u StepNavigationTemplate: cho php hin th Navigation cc bc khng phi bc bt u v kt thc.
http://www.ebook.edu.vn
120
CancelButtonClick: xy ra khi Cancel Button c nhn. FinishButtonClick: xy ra khi Finish Button c nhn NextButtonClick: Xy ra khi Next button c nhn PreviousButtonClick: xy ra khi Previous button c nhn SlideBarButtonClick: xy ra khi SlideBar button c nhn:
Mt iu khin Wizard cha ng mt hoc nhiu WizardStep din t cc bc strong qu trnh Wizard.
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>
<asp:Wizard ID="Wizard1" HeaderText="Wizard control" OnFinishButtonClick="Wizard1_FinishButtonClick" CssClass="wizard" Width="800px" HeaderStyle-CssClass="header" SideBarButtonStyle-CssClass="sideBar" SideBarStyle-Width="200px" SideBarButtonStyle-Width="200px" StepStyle-CssClass="step" runat="server"> <StepStyle CssClass="step"></StepStyle> <WizardSteps> <asp:WizardStep ID="WizardStep1" runat="server" title="Li gii thiu"> <asp:Label ID="Label1" runat="server"
http://www.ebook.edu.vn
122
Text="Cho mng bn n vi trung tm cng ngh cao iTechPRo"></asp:Label> </asp:WizardStep> <asp:WizardStep ID="WizardStep2" runat="server" title="step 1"> <asp:Label ID="Label2" runat="server" Text="Bn bit n iTechPro qua phng tin no"></asp:Label> <br /> <asp:TextBox ID="txt1" runat="server"></asp:TextBox> </asp:WizardStep> <asp:WizardStep ID="WizardStep3" runat="server" StepType="Finish" title="step 2"> <asp:Label ID="Label3" runat="server" Text="Bn thch kho hc no nht iTechPro"></asp:Label> <asp:TextBox ID="txt2" runat="server"></asp:TextBox> </asp:WizardStep> <asp:WizardStep ID="WizardStep4" runat="server" StepType="Complete" title="Tng kt"> <asp:Label ID="Label4" runat="server" Text="Bn bit n iTechPro qua:"></asp:Label> <asp:Label ID="lblbiet" runat="server" Text=""></asp:Label><br /> <asp:Label ID="Label5" runat="server" Text="Bn thch nht kho hc:"></asp:Label> <asp:Label ID="lblkhoahoc" runat="server" Text=""></asp:Label> </asp:WizardStep> </WizardSteps> </asp:Wizard> </div> </form>
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
.content{ background-color:White; border:black 1px solid; width:700px; margin:auto;} .leftcolumm{ float:left; border-right:black 1px solid; width:200px; padding:5px; height:300px} .rightcolumm{ float:left; padding:5px; height:300px} </style> </head> <body> <form id="form1" runat="server"> <div class="content"> <div class="leftcolumm"> <asp:ContentPlaceHolder ID="contentplace1" runat="server"></asp:ContentPlaceHolder> </div> <div class="rightcolumm"> <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </div> </div> </form> </body> </html> s dng MasterPage cho cc trang aspx bn cn khai bo trn ch dn <%@ Page %> vi thuc tnh MasterPageFile=Tn _MasterPage ca bn v d
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
Trinh bay menu Left<br /> Trinh bay menu Left<br /> Trinh bay menu Left<br /> </asp:Content>
<asp:Content ID="content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> Trinh bay noidung<br /> Trinh bay noidung<br /> Trinh bay noidung<br /> Trinh bay noidung<br /> </asp:Content> Trn trang aspx bn khai bo 2 iu khin asp:content v trong thuc tnh ca n bn thit lp ContentPlaceHolderID=Ten_Placeholder trong trang masterPage. To mt Content mc nh Bn khng th kt hp mt iu khin Content vi tt c cc iu khin ContentPlaceHolder. Khi trn trang MasterPage ca bn c 3 ContentPlaceHolder m trong trang aspx ca bn ch s dng hai iu khin aspContent v ch n 2 ContentPlaceHolder trn trang MasterPage khi mc nh ContentPlaceHolder th 3 vn c hin th. ng k Master Page trong WebConfiguration Bn c th p dng MasterPage cho tt c cc trang trong mt Folder hay tt c cc Content trong ng dng web ca mnh. Thay v vic trong mi trang aspx bn phi gi li ch dn trang th ch dn <%@ Page %> th bn c th thm n vo trong file webconfiguration Trong v d di y l cch bn s ng k mt trang SimpleMasterPage vo ng dng web ca mnh c th p dng cho tt c cc trang trong foder(Sub Folder) cha Ch rng file web.config ny phi cng nm trong foleder :
http://www.ebook.edu.vn
126
S dng FindControl trong MasterPage. Khi bn cn chnh sa hay ly thng tin ca 1 iu khin t MasterPage bn c th s dng phng thc FindControl() trong mt Content Page V d
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
Label lbl = (Label)Master.FindControl("lblTitle"); lbl.Text = "Trung tam dao tao cong nghe cao iTechPro"; } </script> <asp:Content ID="content" runat="server" ContentPlaceHolderID="ContentPlaceHolder1"> Lay gia tri tu masterpage<br /> Lay gia tri tu masterpage<br /> Lay gia tri tu masterpage<br /> Lay gia tri tu masterpage<br /> Lay gia tri tu masterpage<br /> </asp:Content> Trnh by thuc tnh MasterPage Bn c th trnh by thuc tnh , phng thc t MasterPage v c th chnh sa thuc tnh hay phng thc t trang Content. V d
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
Property, Property, Property, Property, Property, <br /> Property, Property, Property, Property, Property, <br /> Property, Property, Property, Property, Property,<br /> Property, Property, Property, Property, Property<br /> </asp:Content> Trong v d trn bn s thy mt im mi l ch dn MasterType, s dng c thuc tnh hay phng thc t MasterPage ta phi thm vo ch dn MasterType v t thuc tnh VirtualPath=Ten_Mastepage.
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:
http://www.ebook.edu.vn
131
Trong File simple.skin bn son ni dung nh sau: <asp:TextBox SkinID="txtChidinh" BorderStyle="dashed" BorderWidth="5px" Runat="Server" /> <asp:TextBox BorderStyle="none" BorderWidth="0px" Runat="Server" /> V s dng skin ny cho trang aspx ca chng ta, bn phi thm vo ch dn Theme=simple trong ch dn <%@ Page %>
<!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>Using Themes</title> </head> <body style="background-color:#e5e5e5;"> <form id="form1" runat="server"> <div> <h3>Skin ti iu khin c ch nh</h3> <asp:TextBox ID="txtChidinh" runat="server" SkinID="txtChidinh"></asp:TextBox>
http://www.ebook.edu.vn
132
<h3>Skin mc nh cho iu khin TextBox</h3> <asp:TextBox ID="txtmacdinh" runat="server"></asp:TextBox> <h3>Khng p dng Skin mc nh</h3> <asp:TextBox ID="txtnone" runat="server" EnableTheming="false"></asp:TextBox> </div> </form> </body> </html> kt xut ca chng trnh:
Khi s dng Themes th mc nh nu trong cc iu khin trn Form c quy nh thuc tnh th hin th ca iu khin s b nh hng ca cc thuc tnh . Tuy nhin bn cng c th ghi cc thuc tnh s dng thuc tnh trong Themes quy nh, bng cch a vo ch dn <%@ Page StyleSheetTheme=simple %>. ng k Themes vi web.config Khi bn mun s dng themes cho tt c cc trang web trong website ca mnh bn c th ng k n vo trong file web.config trong ng dng web ca mnh nh sau: <configuration> <system.web> <pages theme=simple /> </system.web> </configuration>
http://www.ebook.edu.vn
133
ghi vo thuc tnh ca iu khin trong website <configuration> <system.web> <pages styleSheetTheme=simple /> </system.web> </configuration> Trong mt trang ta ko mun s dng Themes, ta c th g b n trong trang ny bng cch: <%@ Page Language=C# EnableTheming=false %> Thm CSS ti Themes Css l mt thay th cho skins iu khin cch xut hin ca cc thnh phn ca c HTML v ASPNET Khi thm css vo folder Themes th n s c p dng cho tt c cc trang c p dng theme
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>
v d trn css c s dng ti kiu ca cc thnh phn html, bi v iu khin asp.net a ra m html khi trnh duyt ln p dng css cho cc iu khin ca aspx phi s dng vi th ca HTML, nh trog v d trn c hai iu khin TextBox v Button c a ra m HTML l th <imput>.
http://www.ebook.edu.vn
135
a nhiu CSS vo 1 Themes Khi bn mun a nhiu css vo 1 th mc themes, v d bn to ra hai file css l ThemeA.css v ThemesB.css th khi s dng bn phi dng c php:
<link href=App_Themes/Simple/ThemeA.css type=text/css rel=stylesheet /> <link href=App_Themes/Simple/ThemeB.css type=text/css rel=stylesheet />
TagPrefix: Ch nh khng gian tn m bn mun kt hp usercontrol v trang hin ti TagName: Ch nh tn m bn mun kt hp usercontrol v trang hin ti Src: ch n ng dn ca control(.ascs) V d 1: to mt webcontrol thc hin php tnh ton v s dng n trong 1 trang aspx
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
<asp:Button ID="btnsub" OnCommand="Calculator" CommandName="cal" CommandArgument="sub" runat="server" Text="-" Width="45px" /> <asp:Button ID="btnmul" OnCommand="Calculator" CommandName="cal" CommandArgument="mul" runat="server" Text="X" Width="45px" /> <asp:Button ID="btndiv" OnCommand="Calculator" CommandName="cal" CommandArgument="div" runat="server" Text="/" Width="45px" /> <hr /> <asp:Label ID="lblresult" runat="server" Text="Label"></asp:Label> <hr /> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txta" ErrorMessage="Bn phi nhp a" Visible="False"></asp:RequiredFieldValidator> <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txta" ErrorMessage="a phi l kiu nguyn" MaximumValue="9999999" MinimumValue="0" Type="Integer" Visible="False"></asp:RangeValidator> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtb" ErrorMessage="Bn phi nhp b" Visible="False"></asp:RequiredFieldValidator> <asp:RangeValidator ID="RangeValidator2" runat="server" ControlToValidate="txtb" ErrorMessage="a phi l kiu nguyn" MaximumValue="9999999" MinimumValue="0" Type="Integer" Visible="False"></asp:RangeValidator> <p> </p> <asp:ValidationSummary ID="ValidationSummary1" runat="server" />
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"
<!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>Su dung Webcontrol</title> <style type="text/css"> html{ background-color:#e5e5e5} .divmain{ background-color:White; margin:15px; padding:15px; top:30px; left:150px; position:absolute;} </style> </head> <body> <form id="form1" runat="server"> <div> <div class="divmain"> <main:cal ID="maincal" runat="server" /> </div> </div> </form> </body>
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 m bo kh nng truy xut ng thi ca nhiu ngi dng trn d liu m bo thi gian hi p ngn cho mi ngi dng Bo mt d liu Trao i d liu gia cc h thng khc nhau
Nhng vn ny c gii quyt da vo kh nng ca cc h qun tr c s d liu(HQT CSDL) v cc phn mm x l d liu do HQL CSDL cung cp. Net truy xut d liu qua ADO.NET, c im chnh ca ADO.NET l kh nng lm vic vi d liu khng kt ni, d liu c lu tr trong b nh nh mt csdl thu nh gi l dataset, nhm tng tc tnh ton, x l tnh ton v hn ch s dng ti nguyn trn Database Server. c im quan trng th 2 l kh nng x l d liu chun XML, d liu dng XMl c th trao i gia bt
http://www.ebook.edu.vn
140
Hnh 1
- Managed Provider Component: bao gm cc i tng nh DataAdapter, DataReader, gi nhim v lm vic trc tip vi d liu nh database, file, - Content Component: bao gm cc i tng nh DataSet, DataTable, i din cho d liu thc s cn lm vic. DataReader l i tng mi, gip truy cp d liu nhanh chng nhng forward-only v read-only ging nh ADO RecordSet s dng Server cursor, OpenFowardOnly v LockReadOnly. DataSet cng l mt i tng mi, khng ch l d liu, DataSet c th coi l mt bn sao gn nh ca CSDL trong b nh vi nhiu bng v cc mi quan h. DataAdapter l i tng kt ni gia DataSet v CSDL, n bao gm 2 i tng Connection v Command cung cp d liu cho DataSet cng nh cp nht d liu t DataSet xung CSDL.
Trc khi i vo hc c th cc i tng ca ADO.NET chng ta cng xem qua mt v d HelloWorld vi ADO.NET qua bn s thy c cng vic cn thc hin khi thao tc vi database( v d ny mnh dng vi SQLExpress).
http://www.ebook.edu.vn
141
lm v d ny bn thc hin theo cc bc sau: bc 1. Nhn chut phi vo th mc App_Data chn new Item, Ca s Add New Item hin ra bn chn SqlDatabase nh hnh 1 sau
Hnh 2 bc 2. Nhp tn Database vo hp Name sau nhn Add. Trong Solution Explorer s thm vo Database trong th mc App_Data.
Hnh 3 bc 3. to bng d liu cho Database.mdf o bc 3.1 bn click p chut vo Datatabase.mdf -> Server Explorer hin ra nh sau:
http://www.ebook.edu.vn
142
Hnh 4 o bc 3.2 bn nhn chut phi vo Tables v chn Add New Table
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
public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //chui kt ni n ngun d liu
http://www.ebook.edu.vn
144
string driver = "Data Source=(local)\\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integr ated Security=True;User Instance=True"; //i tng kt ni ti c s d liu SqlConnection sqlconn = new SqlConnection(driver); //Command iu khin truy vn sql SqlCommand sqlcom = sqlconn.CreateCommand(); sqlcom.CommandText = "select sTitle from tblHello where pkHelloID=1"; //m kt ni d liu sqlconn.Open(); //ly v chui gi tr trong c s d liu string result = (string)sqlcom.ExecuteScalar(); //ng kt ni sqlconn.Close(); //in gi tr ra mn hnh Response.Write(result); } } C bn cc bc thc hin vi database bc 1: Ti kt ni bc 2: To lnh iu khin truy vn SQL bc 3:M kt ni d liu bc 4: thc thi lnh bc 5: ng kt ni bc 6: in kt qu
http://www.ebook.edu.vn
145
Khai bo v khi to: SqlConnection sqlcon; string driver="server=localhost; UID=sa; PWD=; database=name_database"; sqlcon=new Sqlconnection(); sqlcon.ConnectionString=driver; Driver l chui kt ni n c s d liu trong trng hp ny mnh kt ni vi sqlserver 2000/2005 Kt ni vi c s d liu Access Bn cn nhp khu lp OleDb using System.Data.OleDb; OleDbConnection oleconn; string driver = "Provider=Microsoft.jet.OLEDB.4.0; Data Source=duongdan_tendata"; oleconn = new OleDbConnection(); oleconn.ConnectionString = driver;
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
Cc phng thc ca i tng Connection Open: cho php m d liu vi cc thuc tnh khai bo trong ConnectString Close: ng c s d liu ang m CreateCommand: phng thc cho php gn hay tr v mt i tng Command ng vi i tng Connection, nh v d HelloWorld SqlConnection sqlconn = new SqlConnection(driver); SqlCommand sqlcom = sqlconn.CreateCommand(); sqlcom.CommandText = "select sTitle from tblHello where pkHelloID=1"; BeginTransaction: Phng thc ny khai bo bt u mt chuyn tc, kt thc chuyn tc bn dng Table Commit Rollback: trong trng hp c li trong qu trnh thc thi bn c th s dng phng thc Rollback hu b cc chuyn tc thc hin. Dispose: dng hu b hay gii phng i tng Connection ang s dng
http://www.ebook.edu.vn
147
IV. i tng SqlDataReader i tng ny c net cung cp c d liu t bng c s d liu, n l i tng ch phc v thao tc c d liu(Read only). Trong khi truy xut d liu n s gi kt ni lin tc vi database(hng kt ni) Khai bo v khi to i tng
SqlDataReader sqlreader; sqlreader = sqlcom.ExecuteReader();
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
Cc thuc tnh bao gm SelectCommand, InsertCommand, UpdateCommand, DeleteCommand: thc hin cc thao tc select, insert, update, delete d liu Phng thc: Fill: Phng thc thc thi cu lnh select trong sql ri in kt qu cho DataSet hoc Datatable. Update: gi lnh cph nht cc thay i vo d liu ln cc d liu ngun in d liu t Adapter vo DataSet Dataset l mt thng cha d liu khng kt ni
public static DataSet Filldataset(string ssql) { DataSet dataset = new DataSet(); opendata(); try { sqladapter = new SqlDataAdapter(ssql, sqlconn); sqladapter.Fill(dataset); sqladapter.Dispose(); } catch (Exception exp) { closedata(); System.Web.HttpContext.Current.Response.Write(exp.ToString()); } closedata(); return dataset; }
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; }
VI. i tng Dataset v DataTable L thnh phn chnh ca kin trc khng kt ni c s d liu, c dng nm gi d liu ca mi c s d liu v cho php thay i d liu bn trong i tng ny sau cp nht tr li c s d liu ngun bng phng thc Update ca i tng DataAdapter
Khi to DataSet dataset = new DataSet(); DataSet dataset = new DataSet("Mydataset");
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
string strQuery = "select * from tblEmployees"; DataSet dataSet = new DataSet("Employees"); try { SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(strQuery, Connection.sqlConnection); sqlDataAdapter.Fill(dataSet); sqlDataAdapter.Dispose(); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } this.dataGridView1.DataSource = dataSet.Tables[0]; //lay ve ten cua doi tuong dataset label1.Text ="DataSetName: " + dataSet.DataSetName ; } private void button2_Click(object sender, EventArgs e) { //khai bao phat bieu sql 1 string strQuery = "select * from tblEmployees"; DataSet dataSet = new DataSet("Employees"); try { SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(strQuery, Connection.sqlConnection); sqlDataAdapter.Fill(dataSet); //khai bao phat bieu sql 2
http://www.ebook.edu.vn
151
strQuery = "select * from tblContracts"; sqlDataAdapter = new SqlDataAdapter(strQuery, Connection.sqlConnection); DataTable dataTable = new DataTable(); sqlDataAdapter.Fill(dataTable); dataSet.Tables.Add(dataTable); sqlDataAdapter.Dispose(); string dataTableName=""; foreach(DataTable dt in dataSet.Tables) { dataTableName += dt.TableName + " "; } label1.Text = "Number of tables: " + dataTableName ; } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } this.dataGridView1.DataSource = dataSet.Tables[1] ; }
Phuong thuc Add, Remove DataSet dataset=new DataSet(); DataTable datatable=new DataTable(datatablename); dataset.Tables.Add(datatable); dataset.Tables.Remove(datatable); xoa voi datatable duoc dat tn dataset.Tables.Remove(datatablename); http://www.ebook.edu.vn 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; } }
V d chng ta s ng dng 3 di tng trn vo vic, cp nht v hin th d liu cho bng sn phm http://www.ebook.edu.vn 154
Bc 1: to bng c s d liu V d chng ta c mt bng d liu tblIntrodure gm cc trng: pkIntrodureID sTitle sSummary iContent iPosition (int) (nvarchar(300) (nText) (nText) (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
Ch : trn l cch to 3 th tc theo c php ca MSSQL nu bn to th tc SQL trong VS th t kho Create s chuyn thnh Alter v GO chuyn thnh Return Bc 3: To cc lp(nm trong th mc App_Code) IntrodureInfo.cs
using System;
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
public static void Insert(IntrodureInfo _introdure) { string[] parameters = new string[7] { "@sTitle", "@sImage", "@sSumary", "@sComment", "@sPage", "@sLang", "@iPosition" }; string[] values = new string[7] { _introdure.sTitle, _introdure.sImage, _introdure.sSumary, _introdure.sComment, _introdure.sPage, _introdure.sLang, _introdure.iPosition.ToString() }; executeData("spIntrodure_insert", parameters, values); } public static void Update(IntrodureInfo _introdure) { string[] parameters = new string[7] { "@pkIntrodureID" ,"@sTitle", "@sImage", "@sSumary", "@sComment", "@sPage", "@iPosition" }; string[] values = new string[7] { _introdure.pkIntrodureID.ToString(), _introdure.sTitle, _introdure.sImage, _introdure.sSumary, _introdure.sComment, _introdure.sPage, _introdure.iPosition.ToString() }; executeData("spIntrodure_edit", parameters, values); } public static void UpdateIndex(string _pkIntrodureID, string _giatri) { string ssql = "update tblIntrodure set iPosition=" + _giatri + " where pkIntrodureID=" + _pkIntrodureID; executeData(ssql); } public static IntrodureInfo Getinfo(string _pkIntrodureID) { DataTable mydata = iTechProData.FillDatatable("spIntrodure_selectbyID", "@pkIntrodureID", _pkIntrodureID); IntrodureInfo _introdure = new IntrodureInfo(); ; _introdure.sTitle = mydata.Rows[0]["sTitle"].ToString(); _introdure.sImage = mydata.Rows[0]["sImage"].ToString();
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
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
protected static SqlConnection sqlconn; protected static SqlCommand sqlcom; protected static SqlDataAdapter sqladapter; protected static DataSet mydata; protected static SqlDataReader sqlreader; #endregion //phuong thuc mo du lieu #region opendata() "M d liu" public static void opendata() { //c chui kt ni t trong file web.config System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader(); string driver = (string)settingsReader.GetValue("hcubiudata", typeof(String)); try { sqlconn = new SqlConnection(driver); if (sqlconn.State != ConnectionState.Open) { sqlconn.Open(); } } catch (Exception exp) { HttpContext.Current.Response.Write("Li m d liu" + exp.ToString()); } } #endregion
http://www.ebook.edu.vn
163
//phuong thuc dong du lieu #region closedata() "ng d liu" public static void closedata() { if (sqlconn.State != ConnectionState.Closed) { sqlconn.Close(); sqlconn.Dispose(); } } #endregion // in d liu vo DataTable t mt th tc trong Database public static DataTable FillDatatable(string store,string _thamso, string _giatri) { opendata(); DataTable datatable = new DataTable(); sqlcom = new SqlCommand(); sqlcom.CommandText = store; sqlcom.Connection = sqlconn; sqlcom.Parameters.AddWithValue(_thamso, _giatri); sqlcom.CommandType = CommandType.StoredProcedure; try { sqladapter = new SqlDataAdapter(sqlcom); sqladapter.Fill(datatable); sqladapter.Dispose(); }
http://www.ebook.edu.vn
164
Trong lp trn bn thy c 2 i tng data mi l DataAdapter v DataTable chng ta s hc k hn trong phn sau trong v d ny cc bn ch cn hiu qua l DataAdapter l b c d liu t ngun d liu, v DataTable l i tng lu tr d liu khng kt ni, n nh mt bng tm cha d liu v n ko cn bit d liu t ngun no.
Bc 4: To giao din s dng
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 </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> style="height:5px;"></td>
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
<asp:TemplateColumn HeaderText="Chnh sa" ItemStyleHorizontalAlign="Center" HeaderStyle-Width="80px" HeaderStyleHorizontalAlign="Center" ItemStyle-Width="100px" ItemStyle-Height="24px" > <ItemTemplate> <asp:LinkButton ID ="Edit" CommandArgument ='<%#DataBinder.Eval(Container,"DataItem.pkIntrodureID")%>' runat ="server" CommandName="Edit" Text ="Edit"></asp:LinkButton> </ItemTemplate> </asp:TemplateColumn> <asp:TemplateColumn HeaderText="Xa" HeaderStyleHorizontalAlign="Center" HeaderStyle-Width="80px" ItemStyleHorizontalAlign="Center" ItemStyle-Width="100px" ItemStyle-Height="24px" > <ItemTemplate> <asp:LinkButton ID ="Delete" CommandArgument ='<%#DataBinder.Eval(Container,"DataItem.pkIntrodureID")%>' runat ="server" CommandName="Delete" Text ="Delete"></asp:LinkButton> </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:DataGrid> </td> </tr> <tr> <td align="right" style="padding-top:3px;"> <asp:Label ID="lblthongbao" runat="server"></asp:Label> <asp:LinkButton ID="lbncapnhatvitri" CssClass="linkbutton" runat="server" Text="Cp nht v tr" OnClick="lbncapnhatvitri_Click" /> </td> </tr> </asp:Panel> </table> </td> </tr>
http://www.ebook.edu.vn
169
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
} } }
Trong on m trn c s dng DataGrid bn s c hc n k hn trong phn sau, by gi bn c coi n nh l mt cng c hin th d liu.
Thuc tnh quan trng DataSource: ch n ngun d liu DataTextField: trng d liu c hin th DataValueField: trng d liu thit lp gi tr vi tng ng vi Text hin th Phng thc OnSelectedIndexChanged
Xy ra khi ngi dng thay i la chn phn t trn DropDownList
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
<!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>DropDownList</title> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_Changed" ID="DropDownList1" runat="server">
http://www.ebook.edu.vn
175
</asp:DropDownList><hr /> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </div> </form> </body> </html>
http://www.ebook.edu.vn
176
iu khin RadioButtonList cho php hin th mt danh sch cc RadioButton m c th sp xp theo hng ngang hay dc, ngi s dng c th chn mt trong cc Radiobutton . V d: khi chng ta cn thm d kin khch hng v mt vn g chng ta cn to mt module bnh chn cho website ca chng ta. Chng ta s thit lp 1 bng sau bng tblSurveyAnswer pkAnswerID sContent iVote iPosition (int) (nvarchar(100)) (int) (int)
<!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>RadioButtonList</title> <style type="Text/css"> body{background-color:#e5e5e5} #navcontain{width:399px;Height:299px;Background-color:white;margin:0px auto; padding:15px 15px 15px 15px;} A:link{COLOR: #31659C; TEXT-DECORATION: none;} A:visited{COLOR: #31659C; TEXT-DECORATION: none;} A:active{COLOR: #FC8800; TEXT-DECORATION: none;} A:hover{COLOR: #FC8800; TEXT-DECORATION: none;}
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>
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
<!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>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div id="navcontain"> iu khin ListBox<br /> <asp:ListBox SelectionMode="Multiple" ID="listbox1" runat="server" /><br /> <asp:Button ID="btnChon" runat="server" Text="Chn" OnClick="btnChon_Click" /><hr /> Bn chn: <asp:Label ID="lblresult" runat="server" /> </div> </form> </body> </html>
http://www.ebook.edu.vn
180
protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) ListControlHelper.fillListBox(listbox1, "tblSurveyAnswer", "sContent", "pkAnswerID"); } protected void btnChon_Click(object sender, EventArgs e) { lblresult.Text = ""; foreach (ListItem item in listbox1.Items) { if (item.Selected) lblresult.Text += "<li>" + item.Text; } } } Trong code 9.8 ta c s dng mt hm fillListBox in d liu vo ListBox bn xem code cui chng. Kt xut ca chng trnh
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" %>
<!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>CheckBoxList</title> </head> <body> <form id="form1" runat="server"> <div id="navcontain"> <b>Bn bit n iTechPro qua</b><br /> <asp:CheckBoxList ID="CheckBoxList1" runat="server"> </asp:CheckBoxList><br /> <asp:Button ID="btnVote" OnClick="btnVote_Click" runat="server" Text=" Vote " /><hr /> Bn chn: <asp:Label ID="lblresult" runat="server" /> </div> </form> </body> </html>
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>"; } } } }
Trong code 9.10 c s dng hm fillCheckBoxList l phng thc ca lp ListControlHelper(xem cui chng) a d liu vo CheckBoxList, trong hm
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" %>
<!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>BulletList Control</title> </head> <body> <form id="form1" runat="server"> <div id="navcontain">
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
Bn c th iu chnh s xut hin ca bullet trong BulletList vi thuc tnh BulletStyle vi cc gi tr c th c sau: Circle, CustomImage, Disc, LowerAlpha, LowerRoman, NotSet, Numbered, Square, UpperAlpha, UpperRoman, Vi thuc tnh c gi tr l CustomImage bn cn ch n ng dn ca nh trong thuc tnh BulletImageURL V d trong Code 9.11 bn thm vo thuc tnh Bulletstyle vi gi tr l Circle bn s thy kt xut ca chng trnh 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"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>GridView</title> </head> <body> <form id="form1" runat="server"> <div id="navcontain">
Transitional//EN"
<asp:GridView AllowSorting="true" DataSourceID="SqlDataSource1" ID="GridView1" runat="server"> </asp:GridView> <asp:SqlDataSource %>" SelectCommand="select * runat="server"></asp:SqlDataSource> </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 ta s in vo thuc tnh from tblIntrodure" ID="SqlDataSource1" ConnectionString="<%$ ConnectionStrings:Gridview
http://www.ebook.edu.vn
187
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:
Bn c th chnh sa trnh by xut hin phn trang theo mnh thay v mc nh n s trnh by bi nhng con s cui ca GridView vi thuc tnh PagerSetting
http://www.ebook.edu.vn
188
PagerSettings-
Lp PagingSetting h tr cc thuc tnh sau: FirtPageImageURL: cho php hin th nh ca lin kt ti trang u tin FirstPageText: Cho php hin th Text ca lin kt n trang u tin LastPageImageUrl: cho php hin th nh ca lin kt ti trang cui cng. LastPageTex: Cho php hin th Text ca lin kt n trang cui cng. Mode: cho php bn la chn hin th kiu cho giao din phn trang, n c th c cc gi tr sau: NextPrevious, NextPreviousFirstLast, Numeric, and NumericFirstLast. NextPageImageUrl: Cho php hin th nh lin kt ti trang tip theo. NextPageText: Text hin th cho lin kt n trang tip theo . PageButtonCount: hin th tng s trang. Position: ch nh v tr hin th phn trang. Gi tr ca n c th l: Bottom, Top, and TopAndBottom. PreviousPageImageUrl: nh hin th cho lin kt ti trang trc . PreviousPageText: Text hin th cho lin kt ti trang trc . Visible: Cho php hin th hay n giao din phn trang.
http://www.ebook.edu.vn
189
V d tip theo chng ta cng customize phn trang 1 GridView vi PagerTemplate GridView nh sau:
http://www.ebook.edu.vn
190
<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"> <PagerTemplate> <table> <tr> <td> <asp:LinkButton id="lnkPrevious" Text="< CommandArgument="Prev" ToolTip="Previous Prev" Page" OnDataBound="GridView1_DataBound"
</td> <td> <asp:Menu id="menuPager" Orientation="Horizontal" OnMenuItemClick="menuPager_MenuItemClick" StaticSelectedStyleCssClass="selectedPage" CssClass="menu" Runat="server" /> </td> <td> <asp:LinkButton CommandArgument="Next" id="lnkNext" Text="Next >" ToolTip="Next Page" Runat="server"
CommandName="Page" />
http://www.ebook.edu.vn
191
</PagerTemplate> </asp:GridView> <asp:SqlDataSource ConnectionString="<%$ConnectionStrings:Gridview %>" SelectCommand="select runat="server"></asp:SqlDataSource> </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" * from ID="SqlDataSource1"
tblIntrodure"
<!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"
Transitional//EN"
http://www.ebook.edu.vn
192
PagerSettings-Mode="NextPreviousFirstLast" Position="TopAndBottom" PagerStyle-HorizontalAlign="Center" AutoGenerateDeleteButton="true" AutoGenerateEditButton="true" DataKeyNames="pkIntrodureID" AllowPaging="true" DataSourceID="SqlDataSource1" ID="GridView1" runat="server"> </asp:GridView> <asp:SqlDataSource %>" ConnectionString="<%$
PagerSettings-
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 where
http://www.ebook.edu.vn
193
Khi nhn vo nt Edit bn s thy cc TextBox s hin ra tng ng vi dng c nhn v chng ta c th thay i d liu trong xc nhn thay i d liu bn nhn Update. Ch rng GridView s t ng a ra CheckBox nu c trng trong bng d liu l Boolean. thay i hay xo d liu bn phi thit lp thuc tnh DataKeyNames vi gi tr l kho chnh trong bng c s d liu ca bn. Hin th d liu trng: GridView bao gm hai thuc tnh cho php bn hin th ni dung cho GridView khi khng c d liu, bn c th s dng EmptyDataText hoc thuc tnh EmptyDataTemplate hin th ni dung khi d liu rng.
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"> <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" PagerSettings-Mode="NextPreviousFirstLast" Position="TopAndBottom" PagerStyle-HorizontalAlign="Center" EmptyDataText="trong bng khng c d liu" DataKeyNames="pkIntrodureID" AllowPaging="true" DataSourceID="SqlDataSource1" ID="GridView1" runat="server"> </asp:GridView> <asp:SqlDataSource %>" SelectCommand="select * from tblHello" ConnectionString="<%$ ConnectionStrings:Gridview PagerSettingsTransitional//EN"
http://www.ebook.edu.vn
194
S dng Fields vi iu khin GridView BoundField: cho php bn hin th gi tr ca cc mc d liu dng Text CheckBoxField: cho php bn hin th gi tr ca d liu di dng CheckBox. CammandField: hin th 1 lin kt cho php chnh sa, xo hay chn dng d liu ButtonField: Cho php hin th d liu nh mt Button(Button, ImageButton, linkButton, Push Button) HyperLinkButton: Cho php hin th d liu nh mt lin kt n mt trang web khc. ImagesField: Cho php bn hin th d liu nh mt nh TemplateField: cho php bn hin th d liu mt cch tu bin vi cc th HTML hoc ASP.NET
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"
<!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
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
public Employee(int _PersonID, string _Hoten, int _Tuoi) { this._PersonID = _PersonID; this._Hoten = _Hoten; this._Tuoi = _Tuoi; } }
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 BoundField: cho php bn hin th gi tr ca d liu nh Text CheckBoxField: hin th d liu di dng mt CheckBox CommandField: hin th lin kt cho php chnh sa, thm mi, xo d liu ca dng. ButtonField: hin th d liu nh mt button(ImageButton, ) HyperLinkField: hin th mt lin kt 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
SelectCommand="select * from tblProduct" runat="server"></asp:SqlDataSource> </div> </form> </body> </html> Kt xut ca chng trnh
Trong v d trn ta a d liu vo DetailView1 vi d liu t bng tblProduct(cha c np d liu), trong DetailView1 ta thm vo thuc tnh EmptyDataText="D liu khng c" khi trong bng khng c d liu chui Text nm trong thuc tnh EmptyDataText s c a ra. Bn cng c th Customize chui text hin th ra khi cha c ni dung EmptyDataTemple nh v d sau: 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> bng
http://www.ebook.edu.vn
202
<form id="form1" runat="server"> <div id="navcontain"> <asp:DetailsView ID="DetailsView1" DataSourceID="SqlDataSource1" runat="server" Height="50px" Width="125px"> <EmptyDataTemplate> <div class="noMatch"> <h1>No Matching Results!</h1> Please select a different record. </div> </EmptyDataTemplate> </asp:DetailsView> <asp:SqlDataSource ID="SqlDataSource1" ConnectionString="<%$ConnectionStrings:hcubiuData %>" SelectCommand="select * from tblProduct" runat="server"></asp:SqlDataSource> </div> </form> </body> </html> Kt xut ca chng trnh s nh sau:
4. Phn trang vi DetailView V d DetailViewPaging.aspx Bn thm vo thuc tnh AllowPaging=true cho iu khin DetailView
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>
<!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">
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
<!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> <style type="text/css"> html{background-color:silver;}
http://www.ebook.edu.vn
206
.content{width:600px;border:solid 1px black;background-color:white;} .intro{border-collapse:collapse;} .intro th,.intro td{padding:10px;border-bottom:1px solid black;} .alternating{background-color:#eeeeee;} </style> </head> <body> <form id="form1" runat="server"> <div id="navcontain"> <asp:Repeater DataSourceID="SqlDataSource1" ID="Repeater1" runat="server"> <HeaderTemplate> <table class="intro"> <tr> <th>Tiu </th> <td>Tm tt</td> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td><%#Eval("sTitle") %></td> <td><%#Eval("sSummary")%></td> </tr> </ItemTemplate> <AlternatingItemTemplate> <tr class="alternating"> <td><%#Eval("sTitle") %></td> <td><%#Eval("sSummary") %></td>
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
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RepeaterEvent.aspx.cs" Inherits="_Default" %> <script runat="server"> void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e) { Response.Write("<li>D liu ang c to</li>"); } void repeater1_DataBinding(object sender, EventArgs e) { Response.Write("Rng buc d liu cho Repeater"); } void Repeater1_ItemCommand(object sender, RepeaterCommandEventArgs e) { switch (e.CommandName) { case "insert": Response.Write(e.CommandArgument.ToString() + ": Bn chn xo d liu"); break; case "update": Response.Write(e.CommandArgument.ToString() + ": Bn chn cp nht d liu"); break; case "delete": Response.Write(e.CommandArgument.ToString() + ": Bn chn xo d liu"); break; } } </script>
http://www.ebook.edu.vn
209
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Repeater</title> <style type="text/css"> html{background-color:silver;} .content{width:600px;border:solid 1px black;background-color:white;} .intro{border-collapse:collapse;} .intro th,.intro td{padding:10px;border-bottom:1px solid black;} .alternating{background-color:#eeeeee;} </style> </head> <body> <form id="form1" runat="server"> <div id="navcontain"> <asp:Repeater OnItemDataBound="Repeater1_ItemDataBound" OnDataBinding="repeater1_DataBinding" OnItemCommand="Repeater1_ItemCommand" DataSourceID="SqlDataSource1" ID="Repeater1" runat="server"> <HeaderTemplate> <table class="intro"> <tr> <th>Tiu </th> <td>Tm tt</td> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td><%#Eval("sTitle") %></td>
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 thc hin cng vic khi d liu c in vo Repeater.
Repeater1_ItemCommand: ph thuc vo tn CommandName a ra cng vic thch hp(nu cha r CommandName bn xem li phn Cc iu khin c bn ca ASP.NET)
<!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">
http://www.ebook.edu.vn
212
<asp:DataList ID="DataList1" DataSourceID="SqlDataSource1" runat="server"> <ItemTemplate> <h3><%#Eval("sTitle") %></h3> Tm tt: <%#Eval("sSummary") %> </ItemTemplate> </asp:DataList> <asp:SqlDataSource ID="SqlDataSource1" ConnectionString="<%$ConnectionStrings:hcubiuData %>" SelectCommand="select sTitle,sSummary,sContent from tblIntrodure" runat="server"></asp:SqlDataSource> </div> </form> </body> </html>
http://www.ebook.edu.vn
213
<form id="form1" runat="server"> <div id="navcontain"> <asp:DataList ID="DataList1" GridLines="Both" RepeatColumns="3" DataSourceID="SqlDataSource1" runat="server"> <ItemTemplate> <h3><%#Eval("sTitle") %></h3> Tm tt: <%#Eval("sSummary") %> </ItemTemplate> </asp:DataList> <asp:SqlDataSource ID="SqlDataSource1" ConnectionString="<%$ConnectionStrings:hcubiuData %>" SelectCommand="select sTitle,sSummary,sContent from tblIntrodure" runat="server"></asp:SqlDataSource> </div> </form> </body> </html> y bn ch cn thm vo hai thuc tnh RepeaterColumns=3 v GridLines=Both kt xut ca chng trnh sau:
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
Tm tt: <%#Eval("sSummary") %><br /><br /> Ni dung: <%#Eval("sContent") %> </ItemTemplate> </asp:DataList> <asp:SqlDataSource ID="SqlDataSource1" ConnectionString="<%$ConnectionStrings:hcubiuData %>" SelectCommand="select pkIntrodureID,sTitle,sSummary,sContent from tblIntrodure" runat="server"></asp:SqlDataSource> <asp:SqlDataSource ID="SqlDataSource2" ConnectionString="<%$ConnectionStrings:hcubiuData %>" SelectCommand="select pkIntrodureID,sTitle,sSummary,sContent from tblIntrodure where pkIntrodureID=@pkIntrodureID" runat="server"> <SelectParameters> <asp:ControlParameter Name="pkIntrodureID" ControlID="DataList1" PropertyName="SelectedValue" /> </SelectParameters> </asp:SqlDataSource> </div> </form> </body> </html> Trong v d trn Datalist1 dng lm menu trong ItemTemplate chng ta a vo mt LinkButton v cung cp cho n thuc tnh CommandName=Select. Ta tip tc a thm vo mt SqlDataSource2 vi vic a vo mt tham s nhn gi tr v t Datalist1 vi tham s truyn pkIntrodureID, v chng ta a thm vo mt Datalist2 vi DataSourceID=SqlDataSource2. Nh vy khi chy chng trnh bn nhn vo mi mc trong Datalist1 th d liu y tng ng s hin trong trong DataList2 Thay i d liu vi iu khin DataList Bn c th s dng DataList thay i d liu bn ghi. Tuy nhin chnh sa d liu ca bn ghi n yu cu nhiu phi vit nhiu code hn so vi cc iu khin rng buc d liu khc nh GridView, FormView hay DetailView. V d sau y s hng dn bn cch thay i v xo d liu t DataList. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Repeateredit.aspx.cs" Inherits="Repeateredit" %> <script runat="server">
http://www.ebook.edu.vn
216
void DataList1_EditCommand(object sender, DataListCommandEventArgs e) { DataList1.EditItemIndex = e.Item.ItemIndex; DataList1.DataBind(); } void DataList1_DeleteCommand(object sender, DataListCommandEventArgs e) { SqlDataSource1.DeleteParameters["pkIntrodureID"].DefaultValue = DataList1.DataKeys[e.Item.ItemIndex].ToString(); SqlDataSource1.Delete(); } void DataList1_UpdateCommand(object sender, DataListCommandEventArgs e) { TextBox txtTitle = (TextBox)e.Item.FindControl("txtTitle"); TextBox txtSummary = (TextBox)e.Item.FindControl("txtSummary"); SqlDataSource1.UpdateParameters["pkIntrodureID"].DefaultValue = DataList1.DataKeys[e.Item.ItemIndex].ToString(); SqlDataSource1.UpdateParameters["sTitle"].DefaultValue = txtTitle.Text; SqlDataSource1.UpdateParameters["sSummary"].DefaultValue = txtSummary.Text; SqlDataSource1.Update(); DataList1.EditItemIndex = -1; } void DataList1_CancelCommand(object sender, DataListCommandEventArgs e) { DataList1.EditItemIndex = -1; DataList1.DataBind(); } </script>
http://www.ebook.edu.vn
217
<!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> <asp:DataList ID="DataList1" DataSourceID="SqlDataSource1" DataKeyField="pkIntrodureID" GridLines="None" OnEditCommand="DataList1_EditCommand" OnDeleteCommand="DataList1_DeleteCommand" OnUpdateCommand="DataList1_UpdateCommand" OnCancelCommand="DataList1_CancelCommand" runat="server"> <ItemTemplate> <h3><%#Eval("sTitle") %></h3> <%#Eval("sSummary") %><br /><br /> <asp:LinkButton ID="lbnedit" runat="server" Text="Edit" CommandName="Edit" /> | <asp:LinkButton ID="lbndelete" runat="server" Text="Delete" OnClientClick="return confirm('Bn c chc chn xo mc ny khng?');" CommandName="Delete" /> </ItemTemplate> <EditItemTemplate> Tiu :<br /> <asp:TextBox ID="txtTitle" runat="server" %>'/><br /><br /> Tm tt:<br /> Text='<%#Eval("sTitle")
http://www.ebook.edu.vn
218
<asp:TextBox ID="txtSummary" runat="server" Text='<%#Eval("sSummary") %>' /><br /><br /> <asp:LinkButton ID="lbnUpdate" runat="server" CommandName="Update" Text="Update" /> | <asp:LinkButton ID="lbncancel" runat="server" CommandName="Cancel" Text="Cancel" /> </EditItemTemplate> </asp:DataList> <asp:SqlDataSource ID="SqlDataSource1" ConnectionString="<%$ConnectionStrings:hcubiuData %>" UpdateCommand="Update tblIntrodure set sTitle=@sTitle, sSummary=@sSummary where pkIntrodureID=@pkIntrodureID" DeleteCommand="Delete from tblIntrodure where pkIntrodureID=@pkIntrodureID" SelectCommand="select * from tblIntrodure" runat="server"> <UpdateParameters> <asp:Parameter Name="pkIntrodureID" /> <asp:Parameter Name="sTitle" /> <asp:Parameter Name="sSummary" /> </UpdateParameters> <DeleteParameters> <asp:Parameter Name="pkIntrodureID" /> </DeleteParameters> </asp:SqlDataSource> </div> </form> </body> </html> Cch thao tc d liu vi DataList gn ging vi FormView. lm c vic ny bn cn cung cp cc button c CommandName ng vi cc phng thc m c DataList h tr . cng vi vic a vo cc tham s tng ng trong thnh phn UpdateParameter v DeleteParameter ca SqlDataSource.
http://www.ebook.edu.vn
219
Form
V d 1: Trang setCookies.aspx
http://www.ebook.edu.vn
220
CodeFile="Default.aspx.cs"
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
protected void Page_Load(object sender, EventArgs e) { int counter=0; if (Request.Cookies["counter"] != null) counter = Int32.Parse(Request.Cookies["counter"].Value); counter++; Response.Cookies["counter"].Value = counter.ToString(); Response.Cookies["counter"].Expires = DateTime.Now.AddYears(2); this.Label1.Text = Response.Cookies["counter"].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" > <head runat="server"> <title>Set Persitent Cookies</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </div> </form> </body> </html> Trong v d trn khi chy chng trnh mi ln bn Refresh li trang th gi tr ca Label1 s tng ln mt. V vi cu lnh Response.Cookies[counter].Expires=Datetime.Now.AddYears(2), c ngha l thi gian tn ti ca Cookie ny s l 2 nm.
c d liu t Cookies
http://www.ebook.edu.vn
222
Bn s dng ln Request.Cookies ly d liu t Cookies, bn xem li v d 2 trang setPersistentCookies.aspx. Khi bn c mt tp hp cc Cookies bn c th ly tt c gi tr ca cc Cookies trn website ca mnh, v d sau y s hng dn bn lm vic . V d 3 trang GetallCookies <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GetAllCookies.aspx.cs" Inherits="GetAllCookies" %> <script runat="server"> void Page_Load() { ArrayList colCookies = new ArrayList(); for (int i = 0; i < Request.Cookies.Count; i++) colCookies.Add(Request.Cookies[i]); grdCookies.DataSource = colCookies; grdCookies.DataBind(); } </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>Get All Cookies</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="grdCookies" runat="server"> </asp:GridView> </div> </form>
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
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SetCookieValues.aspx.cs" Inherits="SetCookieValues" %> <script runat="server"> protected void btnsubmit_Click(object sender, EventArgs e) { Response.Cookies["Person"]["Hoten"] = txtHoten.Text; Response.Cookies["Person"]["Ngaysinh"] = txtNgaysinh.Text; Response.Cookies["Person"]["Color"] = txtColor.Text; Response.Cookies["Person"].Expires = DateTime.MaxValue; } </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>Set Cookie MutilValues</title> </head> <body> <form id="form1" runat="server"> <div> <table> <tr> <td>H tn</td> <td><asp:TextBox ID="txtHoten" runat="server" /></td> </tr> <tr> <td>Ngy sinh</td> <td><asp:TextBox ID="txtNgaysinh" runat="server" /></td> </tr>
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
protected void Page_Load(object sender, EventArgs e) { Session["Message"] = "Hello World"; } </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>Session set</title> </head> <body> <form id="form1" runat="server"> <div> <h1>Session state item added!</h1> </div> </form> </body> </html>
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
<!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>Session get</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lblsession" runat="server" /> </div> </form> </body> </html> Bn lu rng cng nh Cookie khi mt Session c to ra, mt trng thi session c tn ASP.NET_SessionID c t ng thm vo trnh duyt ca bn v Session ny c lu tr trn web server v khng lu tr trn webClient. V khi bn tt trnh duyt i th Session ny ca bn vn tn ti trong khong thi gian quy nh, m ASP.NET Framework quy nh thi gian mc nh ca Session l 20 pht. bn c th thit lp thi gian nhiu hn.
http://www.ebook.edu.vn
228
KeysEnables you to retrieve a list of item names stored in Session state. ModeEnables you to determine the current Session state store provider. Possible values are Custom, InProc, Off, SqlServer, and StateServer. SessionIDEnables you to retrieve the unique session identifier. 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).
i tng HttpSessionState h tr cc phng thc sau: Abandon: Cho php kt thc Session ca mt ngi s dng. Clear: Cho php xo ton b d liu trong Session State. Remove: cho php bn xo tng phn t trong Session State
http://www.ebook.edu.vn
229
Trong v d sau y chng ta thit lp cookieless l AutoDetect nh vy ASP.NET Framework s kim tra s tn ti cu HTTP Cookie header, nu Cookie header c tm thy th Framework s lu tr Session trong mt cookie v ngc li th n s thm vo URL. V d: <configuration> <system.web> <sessionState cookieless="AutoDetect" regenerateExpiredSessionId="true"/> </system.web> </configuration>
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: Name: ch nh tn ca thuc tnh. Type: cho php ch nh kiu d liu ca thuc tnh Defaultvalue: cho php ch nh gi tr mc nh ca thuc tnh ReadOnly: cho php to thuc tnh ch c serializeAs: Enables you to specify how a property is persisted into a static representation. Possible values are Binary, ProviderSpecific, String, and Xml. allowAnonnyMous: cho php ngi s dng nc danh c v thit lp thuc tnh Provider: Cho php bn kt hp thuc tnh vi mt Profile Provider ring bit. customeProviderData:Enables you to pass custom data to a Profile provider.
Sau khi nh ngha mt Profile trong web.config, bn c th s dng i tng Provider chnh sa cc thuc tnh Profile. Nh v d sau y bn s chnh sa hai thuc tnh firstName v lastName trn Form, hn th na chng ta s thy mi ln trang web c load li th gi tr ca NumberOfVisit s tng ln mt. V d: trang showProfile.aspx
http://www.ebook.edu.vn
231
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="showProfile.aspx.cs" Inherits="showProfile" %> <script runat="server"> void Page_PreRender() { firstName.Text = Profile.firstName; lastName.Text = Profile.lastName;
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
<asp:Label ID="lblfistname" runat="server" Text="FirstName:" /> <asp:TextBox ID="txtFirstName" runat="server" /><br /> <asp:Label ID="lbllastName" runat="server" Text="LastName:" /> <asp:TextBox ID="txtLastName" runat="server" /><br /> <asp:Button ID="btnUpdate" Text="Update" runat="server" OnClick="btnUpdate_Click" /> </div> </form> </body> </html> V kt xut ca chng trnh nh sau:
Ch rng thuc tnh ca Profile c trnh by vi kiu d liu quy nh trong thuc tnh type m ta nh ngha trong Profile. Mt thuc tnh quan trng ca Profile n l n c kh nng gi li gi tr ca thuc tnh khi ngi s dng ri khi trang web, v d nu bn gn thuc tnh Profile cho mt ngi s dng, ngi s dng khng quay li website trong 500 nm th gi tr vn c gi li cho ngi s dng. i tng Profile s dng models Provider. mc nh Profile Provider l SqlProfileProvider, Mc nh Provider lu tr d liu Profile trong c s d liu MS SQL Server 2005 Express c t tn l ASPNETDB.mdf, c nh v trong th mc App_Data. Nu c s d liu khng tn ti th n s c to t ng khi chy chng trnh c s dng Profile. Mc nh bn khng th lu tr thng tin Profile cho mt ngi s dng nc danh. ASP.NET Framework tnh ng nht authenticate ca bn kt hp vi thng tin Profile, bn c th s dng i tng Profile vi cc kiu chun m authentication h tr bi ASP.NET Framework, bao gm c hai kim chng Forms v Windows Creating Profile Groups Nu bn cn nh ngha nhiu thuc tnh ca Profile, bn c th to cc thuc tnh bng qun l bi vic t chc cc thuc tnh trong Groups. V d trong file web.config sau nh ngha hai nhm thuc tnh Preferences v ContactInfo. V d Trang web.config
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