`
lu930124
  • 浏览: 28409 次
  • 性别: Icon_minigender_2
  • 来自: 廊坊
文章分类
社区版块
存档分类
最新评论

北大青鸟代码---asp.net初学者宝典

 
阅读更多

一.上传图片:使用控件:file,button,image;

上传按钮的代码:

string fullfilename=this.File1 .PostedFile .FileName ;取得本地文件的全路径如c:/windows//ba.bmp

string filename=fullfilename.Substring (fullfilename.LastIndexOf ("//")+1); 截取文件名:ba.bmp

string type=fullfilename.Substring (fullfilename.LastIndexOf (".")+1); 截取后缀名:bmp

if(type=="jpg"||type=="bmp"||type=="gif") 判断格式是否正确

{

this.File1 .PostedFile .SaveAs (Server.MapPath ("UP")+"//"+filename);保存在UP文件夹里

this.Image1.ImageUrl="UP/"+filename; 在页面上显示图片

}

else

{Response.Write("<script language='javascript'>alert('嘿嘿~~格式错误~~');</script>");}

二.简单的用户登陆:

登陆界面的代码:先要引用命名空间:using System.Data.SqlClient;

string username=Request.Form["username"].ToString(); post方法提交

string userpwf=Request.Form.Get("userpwf").ToString();

SqlConnection con=new SqlConnection("server=.;database=aa;UID=sa;pwf= ;");

con.Open(); 打开连接

SqlCommand cmd= new SqlCommand("select count(*) from user where username='"+username+"'and userpwf='"+userpwf+"'",con);

int count=Convert.ToInt32(cmd.ExecuteScalar());返回首行首列,返回的是对象类型,所以要转换

if(count>0)

{ Response.Redirect("main.aspx"); }

else

{ Response.Redirect("loginfail.htm"); }

主页面的代码:string username=Request.QueryString["username"].ToString();

Response.Write("<fron size=24 color=red> 欢迎"+username+"光临本网站</font>");

登陆页面的HTML代码:登陆失败返回 登陆失败〈a href=”login.htm”>返回</a>

三.网上投票:在数据库中新建2个表

表一:votemaster

Voteid

Votetitle

Votesum

1

选举工会

0

2

对网站的建议

0

表二: votedateils

voteID

voteDetailsID

voteIteam

voteNum

1

1

于海涛

0

1

2

王晓刚

0

1

3

王磊

0

2

1

非常好

0

2

2

0

2

3

一般

0

2

4

需要改进

0

(1) 先要引用命名空间:using System.Data.SqlClient;

(2)在public class vote中加上private string voteID="1";来决定是进行哪类投票

(3)绑定数据库: private void Page_Load(object sender, System.EventArgs e)

{ if(!this.IsPostBack)

{

{//创建连接

SqlConnection con=DB.createConnection();

con.Open();

//查询选举的标题

SqlCommand cmd=new SqlCommand("select votetitle from votemaster where voteid="+this.voteID,con);

string title=Convert.ToString(cmd.ExecuteScalar ());

this.lbltitle.Text=title;

//查询对应的项目条目

SqlCommand cmdItem=new SqlCommand ("select voteid,votedetails from votedateils where voteID="+this.voteID,con);

SqlDataReader sdr=cmdItem.ExecuteReader();

this.Rblitem.DataSource =sdr;

this.Rblitem.DataTextField="votedetails";

this.Rblitem.DatavalueField="voteid";

this.Rblitem .DataBind ();

sdr.Close();

con.Close();}

}

(4)投票按钮代码: SqlConnection con=DB.createConnection();

con.Open ();

SqlCommand cmd=new SqlCommand ();

cmd.Connection =con;

cmd.CommandText="update votedateils set votenum=votenum+1 where voteID="+voteID+"and votedetailsid="+this.Rblitem .Selectedvalue .ToString();

cmd.ExecuteNonQuery();

//更新

con.Close ();

(5).为了统计票数的总数,要在数据库里建立一个触发器,代码如下:

create trigger updataMaster

on votedateils

for update

as

begin

update voteMaster set votesum =votesum+1 where voteid=(select voteID from inserted)

end

(6)点击结果按纽的代码:Response.Redirect ("showResult.aspx?void="+this.voteID );

(7)showsesult.aspx.cs的page-load代码:

string voteID=Request.QueryString["voteid"].ToString() ;

SqlConnection con=DB.createConnection();

con.Open();

//查询对应的项目条目

SqlCommand cmdItem=new SqlCommand ("select voteid,votedetails from votedateils where voteID="+voteID,con);

SqlDataReader sdr=cmdItem.ExecuteReader();

while(sdr.Read ())

{

Response.Write ("<font size=15>"+sdr.GetString (2)+"-"+sdr.GetInt32 (3).ToString ()+"</font><br>");

}

sdr.Close();

con.Close();

四.Button使用方法:

Button:command属性:多个button时可以通过设置的数值来判断按了哪个

Linkbutton:和button属性一样

Imagebutton:imageUrl属性:显示的图片(必须在项目里新建文件夹,把文件放在里面)

Alternatetext:当图片不存在或鼠标在图片停留时显示的文字

Hypelink:NavigateUrl属性:连接到本地的网页

imageUrl属性:显示的图片(必须在项目里新建文件夹,把文件放在里面)

也可以在page.load上写代码:

this.HyperLink1 .NavigateUrl ="ftp://192.168.1.11";

优点:可以动态的改变链接,用于直接链接,不需要发送给服务器,比较快

五.内部控件:checkbox:chexked(true,false)

Autopostback:当选择信息时会自动提交给服务器,设为false时不响应(应该少用)

Radiobutton:groupname属性:设成组

CheckBoxList:RepeatDrection:显示的方向 Repeatcounts:每行显示的个数

六.用CheckBoxList1连接数据库做一个爱好选择

1.新建一个数据库连接类:添加---添加类using System.Data .SqlClient ;

创建连接函数: public static SqlConnection creteConnection()

{System.Data .SqlClient.SqlConnection con=new SqlConnection("server=.;database=login;UID=sa;pwd=;");

return con;}

2. 页面显示时列出所有爱好:

if(!this.IsPostBack )

{ SqlConnection con=DB.creteConnection() ;

con.Open();

SqlCommand cmd= new SqlCommand("select * from pernonlike",con);

SqlDataReader sdr=cmd.ExecuteReader ();

this.CheckBoxList1 .DataTextField ="likecontent";

this.CheckBoxList1 .DatavalueField ="id";

this.CheckBoxList1 .DataSource =sdr;

this.CheckBoxList1 .DataBind ();

sdr.Close();

con.Close ();}

3.把选中的爱好列出来:

for(int i=0;i<this.CheckBoxList1 .Items .Count -1;i++)

{if(this.CheckBoxList1 .Items [i].Selected )

{Response.Write (this.CheckBoxList1 .Items [i].Text +"<br>");}}

七.省和市绑定:

1.新建类:public static SqlConnection createConnection()

{

SqlConnection con=new SqlConnection ("server=.;database=aa;UID=sa;Pwd=;");

return con;}

2.网页打开时显示所有的省和市: if(!this.IsPostBack )

{ SqlConnection con=DB.createConnection() ;

con.Open ();

//绑定省

SqlCommand cmd=new SqlCommand ("select * from province",con);

SqlDataReader sdr=cmd.ExecuteReader ();

this.DropDownList1 .DataSource =sdr;

this.DropDownList1.DatavalueField ="proID";

this.DropDownList1 .DataTextField ="proName";

this.DropDownList1 .DataBind ();

sdr.Close ();

//绑定市

SqlCommand cmdcity=new SqlCommand ("select * from city where proID="+this.DropDownList1 .Selectedvalue ,con);

sdr=cmdcity.ExecuteReader ();

this.DropDownList2 .DataSource =sdr;

this.DropDownList2 .DataTextField ="cytiName";

this.DropDownList2 .DatavalueField ="cytiID";

this.DropDownList2 .DataBind ();

sdr.Close ();

con.Close ();}

3.选择省时自动选择相应的市:省的DropDownList1的Autopostback设为true;

省的DropDownList1_SelectedIndexChanged事件:

string proID=this.DropDownList1 .Selectedvalue ;

SqlConnection con=DB.createConnection ();

con.Open ();

SqlCommand cmd=new SqlCommand ("select * from city where proID="+proID,con);

SqlDataReader sdr=cmd.ExecuteReader();

this.DropDownList2 .DataSource =sdr;

this.DropDownList2 .DataTextField ="cytiName";

this.DropDownList2 .DatavalueField ="cytiID";

this.DropDownList2 .DataBind ();

sdr.Close ();

con.Close ();

八:复杂控件:ADROtator的用法:一个<ad><./ad>包含一个广告

.xml文件中的内容:<advertisements>

<ad>

<imageUrl></imageUrl>:图象文件的绝对或相对路径;

<NavigateUrl></NavigateUrl>:单击后访问的目标web站点

<Alternametext></Alternametext>鼠标在图象上移动时显示的文本

<Keyword></Keyword>:指定给此AD的类别 数值

<Impressions></impressions>在循环播放时间安排中广告的优先级,通过刷新显示

</advertisements>

</ad>

Advertisementfile属性:所要选择的.xml文件 还要把图片放在同一个目录下

Target属性:_blank 通过使用空白网页打开连接的网址

KeywordFilter属性:显示哪个分组广告,即Keyword的值

九.Calendar日历控件

显示选择日期:this.Label1 .Text =this.Calendar1 .SelectedDate .ToShortDateString ();

十.验证控件

1.RequiredFieldValidator 限制空字段

ErrorMessage:填写的文本(一般用*)

ControlTovalidata:与哪个控件相关联

Display:static:静态的,显示和不显示都占空间;dynamic:动态的,显示时占空间,不显示不占空间

2.Comparevalidator:比较字段,3种情况:

A.固定值比较 valuetocompare 固定的值比较

Type:表示固定值的类型

Operator:比较的运算符,如:大于,小于,不等于

B.类型检查:如检查日期:1985-12-7

Type:data operator:datatypecheck

C:控件比较:如密码是否一样

ControlTovalidata:与哪个控件相关联

Controltocompare:和这个控件相比较

Textmode:password;

3. Rangevalidator检查指定范围

Maximunvalue:范围的最大值 Minimunvalue:范围的最小值

4.RegularEcpressionValidator:使用表达式检查值

ValidationExpression:选择表达式

5.Customvalidator:通过客户端或服务器端函数检查值 如:验证用户是否存在

在ServerValidate事件中,有2个参数:source:数据源 args参数:value表示文本中的值,isvalid表示是否通过验证

string userName=args.value ;

SqlConnection con=new SqlConnection ("server=.;database=aa;uid=sa;pwd=;");

con.Open ();

SqlCommand cmd=new SqlCommand ("select count(*) from user1 where username='"+userName+"'",con);

int count=Convert.ToInt32 (cmd.ExecuteScalar());

if(count>0)

{args.IsValid =false;}

else

{args.IsValid =true;}

con.Close ();

6.Validationsummary:在页面中列出所有控件的验证错误

7.page.IsValid:如果整个页面的控件都通过验证,它的值为true,否则,它的值为false;

十一.不支持本地验证,要求所有的验证都提交到服务器去验证,避免出错

方法:在html页的第一行加上 ClientTarget=”downlevel”

十二. Application 是对象类型,可以存储任何对象定义的都是全局变量

Application.add有两个参数,一个是string,一个是object

“ Application.Lock() //防止并发控制,对用户的锁定,在同一时间,只能保证一个用户对它处理

Application.Unlock()

在线人数的统计:

.aspx文件:在Application_Start写如

Application.Add ("count",0);或Application["count"]=0;

在Session_Start写:

Application.Lock();//哪个会话将它锁定哪个会话就能帮它修改;

Application["count"]=(int)Application["count"]+1;注意:Application["count"]的返回值是对象类型所以要转换

Application.Unlock();解锁

在page_onload上写:Response.Write (Application["count"].ToString() );

Application所存的值是对象类型,而所有的父类都是object,所以父类的指针可以用任何子类的指针去实例化,object可以存储所有的对象,包括数组:如:

存储数组按纽代码: string[] a=new string[3];

a[0]="教员";

a[1]="班主任";

a[2]="工人";

Application.Add("b",a);

读取数组按纽代码:string[] c=(string[])Application["b"];

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

{this.ListBox1.Items .Add (c[i]);}

Application在会话中起到共享的作用,当存储数组后,打开另一个网页后依然可以读取数据

十三.server:ScriptTimeout属性:用于指定脚本在终止之前在服务器上运行的时间周期

MachineName属性:用于获取服务器上的计算机名

MapPath方法:请求服务器上的某一个相对路径,然后求出它的绝对路径(服务器上的虚拟路径对应的绝对路径是什么)

Execute方法:一个页面去执行另一个界面,执行完的结果返回原来的页面,控制权在原来的页面,但是redirect就不会

HTMLEncode方法:将HTML的标记按文本显示出来

UrlEncode方法:在URL的特殊字符显示出来

十四.Session(会话,一个客户与服务器间的交互叫做一个会话):优点:

1.包含用户特定信息 2.在会话中跟踪和监视用户信息 3.会话期满后销毁对象

十五.记录历史访问人数和当前在线人数

1. 建立数据库 countpeople的表countpeople 的字段 int count 初始值为0

// Global.axpx文件:记录里所有应用程序集和会话程序集的事件

2. protected void Application_Start(Object sender, EventArgs e)

{ SqlConnection con=new SqlConnection ("server=.;database=countpeople;uid=sa;pwd=;");

con.Open();

SqlCommand cmd=new SqlCommand ("select * from countpeople",con);

int count=Convert.ToInt32 (cmd.ExecuteScalar());

con.Close();

Application["totol"]=count;

Application["online"]=0;

}

3. protected void Session_Start(Object sender, EventArgs e)

{ Session.Timeout =1;//设置超时时间为1分钟,就是一分钟没有和服务器响应才离线,超时才能离线

Application.Lock ();

Application["totol"]=(int)Application["totol"]+1;

Application["online"]=(int)Application["online"]+1;

Application.UnLock ();

}

4. protected void Session_End(Object sender, EventArgs e)

{ Application.Lock ();

Application["online"]=(int)Application["online"]-1;

Application.UnLock ();

}

5. protected void Application_End(Object sender, EventArgs e)

{ SqlConnection con=new SqlConnection ("server=.;database=countpeople;uid=sa;pwd=;");

con.Open();

SqlCommand cmd=new SqlCommand ("update countpeople set num="+Application["totol"].ToString (),con);

int count=Convert.ToInt32 (cmd.ExecuteScalar());

cmd.ExecuteNonQuery ();

con.Close();

}注意:一般执行到Application_End时只有关机,但是因为可以开始---设置---控制面版---管理工具—服务

停止word wide web 就相当于关机,然后再启动就可以拉

十四:在登陆时,有时候可以直接输入页面的代码进入页面,所以应该在每个页面来判断是否登陆了,以下方法为判断1.是否为正确登陆:登陆按钮的代码:if (TextBox1.Text=="a")

{ Session["flag"]=true;

Response.Redirect ("main.aspx"); }

2.在main页面的page_onload事件上写:if (Session["flag"]==null)

{ Response.Redirect ("WebForm1.aspx"); }//如果失败就返回原来的界面

3.在每一页的page_onload事件上写:Server.Execute(“main.aspx”);

十五. ADO.net

1. RxecuteNonQuery():一般执行数据的增,删,改

2. DataAdaper 数据适配器是ADO.net托管提供程序的组成部分,用于在数据源和数据集之间交换数据,它主要有4个命令对象,selectcommand,insertcommand,updatecommand,delectcommand

十六.插入用户,如果插入成功就在DataGrid上显示所有用户,可以进行修改,删除,查询

1. 新建数据库adonettext,新建表person :pID varchar 10 pName varchar 50 pSex varchar 2

2.新建一个实体类person: public class person

{ public string pID;//定义一个实体类

public string pName;

public string pSex

2. 新建一个操作类:personoperate 使用命名空间:using System.Data .SqlClient ;using System.Data

3. 以下是在操作类的代码:

public static SqlConnection createconnection() //建立数据库连接

{return new SqlConnection ("server=.;database=adonettext;uid=sa;pwd=;");}

public static bool FindPerson(string pID)//判断用户是否存在

{ SqlConnection con=personoperate.createconnection ();

con.Open();

SqlCommand cmd=new SqlCommand ("select count(*) from person where pID='"+pID+"'",con);

int count=Convert.ToInt32 (cmd.ExecuteScalar());

if (count>0)

{ return true; }

else

{ return false; }

}

public static DataTable selectAllPerson() //检索datagrid上显示数据

{ SqlConnection con=personoperate.createconnection ();

SqlDataAdapter sda=new SqlDataAdapter (); //创建DataAdaper 数据适配器对象,使用它时数据库会自动打开

sda.SelectCommand=new SqlCommand ("select * from person",con);

DataSet ds=new DataSet ();//使用数据集

sda.Fill (ds,"person"); //填充数据集

return ds.Tables ["person"];

}

public static bool insertOperate(person p)//添加用户

{ try

{ SqlConnection con=personoperate.createconnection ();

con.Open();

SqlCommand cmd=new SqlCommand ("insert into person values(@pID,@pName,@pSex)",con);//使用参数

SqlParameter para=new SqlParameter ("@pID",SqlDbType.VarChar,10);//3个参数,参数值,类型,长度

para.value =p.pID ;

cmd.Parameters .Add (para);//添加到集合里

para=new SqlParameter ("@pName",SqlDbType.VarChar,50);

para.value =p.pName ;

cmd.Parameters .Add (para);

para=new SqlParameter ("@pSex",SqlDbType.VarChar,2);

para.value =p.pSex ;

cmd.Parameters .Add (para);

cmd.ExecuteNonQuery ();//执行

return true;

}

catch( Exception e)//将出现的错误捕获

{ return false; }

}

ublic static bool updataOperate(person p)

{

try

{

SqlConnection con=personoperate.createconnection();

con.Open();

SqlCommand cmd=new SqlCommand("update person set personName='"+p.pName+"',personSex='"+p.pSex+"' where pID='"+p.pID+"'",con);

cmd.ExecuteNonQuery();

return true;

}

catch(Exception e)

{

return false;

}

}

public static bool delectOperate(string pID)

{

try

{

SqlConnection con=personoperate.createconnection ();

con.Open();

SqlCommand cmd=new SqlCommand("delete from person where pID='"+pID+"'",con);

cmd.ExecuteNonQuery();

return true;

}

catch (Exception e)

{

return true;

}

}

4. 在自定义验证控件的ServerValidate事件中写如下代码,来判断是否存在该用户:

string pID=args.value;

if( personoperate.FindPerson(pID))

{ args.IsValid =false; }

else

{ args.IsValid =true; }

5. 在webform1.apx.cs中定义一个绑定控件的事件:

private void fillDg() //绑定方法

{ this.DataGrid1 .DataSource =personoperate.selectAllPerson();//绑定数据源

this.DataGrid1.DataBind ();// 绑定表格 }

6. 在添加按纽的点击事件上写:

if(this.IsValid ) // 是否整个页面的控件都通过验证

{ person p=new person ();

p.pID =this.Txtid .Text ;

p.pName =this.Txtname .Text ;

if(this.rbtnnan.Checked )

{ p.pSex ="男"; }

else

{ p.pSex ="女"; }

if(personoperate.insertOperate(p))

{ Response.Write ("插入成功");

this.fillDg (); }

else

{ Response.Write ("插入失败!");}

}

7. 修改按纽的代码:

// 要先判断用户是否存在

if(!this.CustomValidator1 .IsValid )

{

person p=new person ();

p.pID =this.Txtid .Text ;

p.pName =this.Txtname .Text ;

if(this.rbtnnan.Checked )

{ p.pSex ="男"; }

else

{ p.pSex ="女"; }

if(personoperate.updataOperate(p))

{

Response.Write ("更改成功");

this.fillDg ();

}

else

{ Response.Write ("更改失败!"); }

}

8. 删除按纽的代码:

if(!this.CustomValidator1 .IsValid )

{ if(personoperate.delectOperate(this.Txtid.Text))

{

Response.Write ("删除成功");

this.fillDg ();

}

else

{ Response.Write ("删除失败!"); } }

9. 查询按纽的代码:

//causesValidation 是否引发验证 把它设为false

string c="";

if(this.ChkPID .Checked )

{

if(this.Txtid.Text=="")

{ c="pID like '%'"; }

else

{ c="pID="+this.Txtid.Text; }

}

else

{ c="pID like '%'"; }

if(this.ChkName .Checked )

{

c+=" and personName like '%"+this.Txtname.Text+"%'";

}

if(this.ChkSex.Checked)

{

if(this.rbtnnan .Checked)

{c+="and personSex='男'"; }

else

{ c+="and personSex='女'"; }

}

//新建一个视图,视图是基于datatable

DataView dv=new DataView (personoperate.selectAllPerson());//personoperate.selectAllPerson生成一个table对象

dv.RowFilter =c;

dv.Sort="pID Desc";

this.DataGrid1 .DataSource =dv;

this.DataGrid1.DataBind();

}

十七:做一个用户注册的界面

1.插入4个pannel,在pannel里面插入HTML的表格,要合并时在HTML代码里面改,表格的宽高都设为100%

2.建立样式表,使字体不随着浏览器的变化而变化,

在HTML里:的<head></head>里面写:那么整个网页的字体都是12了~~~嘿嘿

<style type=text/css> Table{font-size:12;} </style>

如果单独的字体要变化,那么就选择字体,右键---生成样式

十八.在DataGrid.读取XML文档

1.新建一个叫student的XML文档,输入部分数据,如<student>

<stusent>

<name>dd</name>

<sex>男</sex>

<age>21</age>

</stusent>

</stusent> 然后在数据部分填写数据

3. 在主页面使用命名空间:Using System IO;

4.在page_onload里写入:FileStream fs=new FileStream(Server.MapPath("student.xml"),FileMode.Open,FileAccess.Read);

//新建文件流 参数1:文件路径 参数2:对文件操作的模式 参数3:文件存取的模式

StreamReader sr=new StreamReader(fs);//读取或写入纯文本

DataSet ds=new DataSet ();//创建一个数据集对象

ds.ReadXml(sr);

this.DataGrid1 .DataSource =ds.Tables [0];

this.DataGrid1.DataBind();

十八:复习以前的内容,使用server application 以及一些封装的应用,是一个用户是否通过验证的例子:1.

1. 新建一个叫做user的类,来存储用户的信息:public string name;public string identity; //身份

2. 在global.asax中的Application_Start中定义一个全局变量,来记录在线人数:

Application.Add ("count",0);

3.在global.asax中的Session_Start中即会话开始的时候记录人数:Application.Lock ();

Application["count"]=(int)Application["count"]+1;

Application.UnLock ();

5.关闭当前窗口:在page_onload事件里写:this.Button4.Attributes .Add("onclick","window.close()");

6..login的登陆按钮代码:Session["flag"]="ok";

user u=new user();

u.name =this.TextBox1 .Text ;

u.identity =this.DropDownList1 .Selectedvalue ;

Session["user"]=u;

Response.Redirect ("main.aspx");

10. 在做一个页面来判断用户是否合法登陆,这样可以直接调用,不用没次都写,比较方便

在dujge页面中的on_load中写:if(Session["flag"]==null||(string)Session["flag"]!="ok")

{Response.Redirect ("loginfail.aspx");}

8.在主界面就可以调用它了:Response.Write("当前在线人数是:"+Application["count"].ToString());//显示在线人数 Response.Write ("<br>");

Server.Execute ("judge.aspx"); //使用Execute方法,页面最终的决定权着这个页面

user u=(user)Session["user"];

Response.Write ("用户名是:"+u.name );

Response.Write ("<br>");

Response.Write ("身份证是:"+u.identity);

9.登陆失败loginfail.aspx的代码为:Response.Write("您未登陆,请登陆.....");

Response.Write ("<br>");

Response.Write ("<a href=login.aspx>返回</a>");

十九:数据绑定

1.简单绑定:格式:<%# textbox1.Text %> 将控件绑定到 textbox1上

2.绑定的命名容器:DataBinder.Eval()方法:3个参数:数据项的命名容器,数据字段名,格式字符串

3.将一个表绑定到DataList上

(1) 使用DataList 自己定义一个table :在page_onload上写:

if(!this.IsPostBack )

{

DataTable dt=new DataTable();

dt.Columns .Add ("num",typeof(int));

for(int i=0;i<10;i++)

{

DataRow dr=dt.NewRow ();

dr[0]=i;

dt.Rows .Add (dr);//将这一行添加到集合中

}

this.DataList1 .DataSource =dt;

this.DataList1 .DataBind ();

}

(2).指定DataList的绑定表达式

在HTML页中的<asp:DataList id="DataList1" s…….: .></asp>中

<ItemTemplate> //项目循环显示的模板

数字:<%# ((DataRowView(Container.DataItem)[“num”] %> //返回的是对象类型,所以要转换问视图中的一行

平方:<%# (int) ((DataRowView(Container.DataItem)[“num”]* (int) ((DataRowView(Container.DataItem)[“num”] %>

货币:<%# DataBinder.Eval(Container.DataItem,”num”,”${0}”) %>{0}表示字段”num”的值,{0:c}

表示按人民币来显示,{0:p}表示按百分数来显示

<ItemTemplate>

注意:使用DataRowView要导入命名空间:<%@ Import Namespace=”System.Data”%>

3. repeater模板:ItemTemplate:正常显示

Alternating ItemTemplate:交错显示

HeaderTemplate:模板页眉

FlooterTemplate:模板页脚

Separator:数据间分隔

例如:使用repeater模板绑定显示表中的字段,并且分页浏览数据:

(1)新建一个方法:

private void DataBindToRepeater()

{

int curPage=Convert.ToInt32(this.Label2 .Text) ;

SqlConnection con=DB.createconnection();

SqlDataAdapter sda=new SqlDataAdapter();

sda.SelectCommand =new SqlCommand("select * from Employees",con);

DataSet ds=new DataSet();//定义一个数据集

sda.Fill (ds,"emp1");//使用数据适配器来填充数据集

PagedDataSource ps=new PagedDataSource ();//一个能实现分页功能的DataSource

ps.DataSource =ds.Tables ["emp1"].DefaultView ;//数据源设置为表的视图

ps.AllowPaging =true; //允许分页

ps.PageSize =3; //每行显示3条记录

ps.CurrentPageIndex =curPage-1;//CurrentPageIndex表示显示的页码,默认第一页是第零页

this.Button1 .Enabled =true;

this.Button2 .Enabled =true;

if(curPage==1)

{

this.Button1 .Enabled =false;

}

if(curPage==ps.PageSize)

{

this.Button2.Enabled=false;

}

this.Repeater1 .DataSource =ps;

this.Repeater1.DataBind();

}

(2)显示表中的某个字段:在HTML页中:

<ItemTemplate>

<%# DataBinder.Eval(Container.DataItem,"LastName")%>

<%# DataBinder.Eval(Container.DataItem,"FirstName")%>

</ItemTemplate>

<AlternatingItemTemplate>

<font color =blue>

<%# DataBinder.Eval(Container.DataItem,"LastName")%>

<%# DataBinder.Eval(Container.DataItem,"FirstName")%>

</font>

</AlternatingItemTemplate>

<HeaderTemplate>

<h3 >模板页眉</h3>

</HeaderTemplate>

<FooterTemplate>

<h3 >模板页脚</h3>

</FooterTemplate>

<SeparatorTemplate>

<hr color ="bile" size ="1">

</SeparatorTemplate>

(3) Page_load事件中:if(!this.IsPostBack )

{

this.Label2 .Text ="1";

this.DataBindToRepeater ();

}

(4)“上一页”按纽的代码:this.Label2.Text=Convert.ToString (Convert.ToInt32(this.Label2.Text)-1);

this.DataBindToRepeater (); //每提交一次都要绑定控件一次

4. 使用DataList绑定表中的数据:

(1).定义方法绑定数据

private void DataBindToDataList()

{

SqlConnection con=DB.createconnection();

SqlDataAdapter sda=new SqlDataAdapter();

sda.SelectCommand =new SqlCommand("select * from Employees",con);

DataSet ds=new DataSet();//定义一个数据集

sda.Fill (ds,"emp1");//使用数据适配器来填充数据集

this.DataList1.DataKeyField="EmployeeID"; //保存主键,以便更新的时候按主键去更新

this.DataList1.DataSource =ds.Tables["emp1"];

this.DataList1.DataBind ();//以上代码进行了数据绑定

}

(2)在page_onload调用:if(!this.IsPostBack )

{ this.DataBindToDataList(); }

(3)在HTML中写入:<ItemTemplate>

<%# DataBinder.Eval(Container.DataItem,"LastName") %>

<%# DataBinder.Eval(Container.DataItem,"FirstName") %>

</ItemTemplate>

(4)在DataList使用右键——编译生成器或者使用项模板

选择一项后显示本行的详细信息

在ItemTemplate中添加LinkButton,text改为查看详细信息,在HTML页中把添加LinkButton的代码向上移一行

在项模版中选择LinkButton,把Commandname属性改为select

(5).选择DataList的ItemCommand事件:注意,如果在选项中有按纽无论点击了哪个按纽都会触发该事件

(6)绑定:if(e.CommandName=="select")

{

this.DataList1.SelectedIndex=e.Item .ItemIndex ;

this.DataBindToDataList (); //绑定

}

(7).绑定后显示:在HTML中写:<SelectedItemTemplate>

员工姓名:<%# DataBinder.Eval(Container.DataItem,"LastName") %>

<br>

生日:<%# DataBinder.Eval(Container.DataItem,"BirthDate","{0:D}") %>

<br> //D表示显示日期

住址:<%# DataBinder.Eval(Container.DataItem,"Address") %>

</SelectedItemTemplate>

(8).修改信息:在ItemTemplate中添加LinkButton,text改为编辑,在DataList1的EditCommand事件中写:

this.DataList1.EditItemIndex=e.Item.ItemIndex;

this.DataBindToDataList;

在项模版中的EditItemTemplate中添加2个LinkButton,text 为更新和取消,commandname设置为upname和cannel,添加一个text,改名为txtcity,并将城市这条记录绑定在text上

在HTML中,首先,要显示一个固定的名字,这个名字是不能编辑的,然后,在项模板选择tetcity,选择Databings,自定义表达式:DataBinder.Eval(Container.DataItem,"City")

取消:在CancelCommand中:

this.DataList1.EditItemIndex=-1; //表示一个也没有选中

this.DataBindToDataList();

更新:UpdateCommand中:string empID=this.DataList1.DataKeys[e.Item.ItemIndex].ToString();

//DataKeys是一个集合,是按照索引的顺序存储所有主键,这里就取出了主键

string city=((TextBox)e.Item.FindControl("txtcity")).Text;//查找控件,并取出它对应的值

//更新到数据库

SqlConnection con=DB.createconnection();

SqlCommand cmd=new SqlCommand("update Employees set city='"+city+"' where EmployeeID ='"+empID+"'",con);//条件是EmployeeID等于我们取出来的主键

con.Open ();

cmd.ExecuteNonQuery();

this.DataList1.EditItemIndex=-1; //把编辑的索引设置为-1;

this.DataBindToDataList();//重新绑定

二十.复习十九的内容:数据绑定在DataGrid,和一些小技巧

1.新建DB类: public static SqlConnection createconnection() //建立数据库连接

{ return new SqlConnection ("server=.;database=Northwind;uid=sa;pwd=;"); }

2.定义绑定数据的方法:SqlConnection con=DB.createconnection();;

SqlDataAdapter sda=new SqlDataAdapter();

sda.SelectCommand =new SqlCommand ("select EmployeeID,LastName,FirstName,Title, BirthDate from Employees",con);

DataSet ds=new DataSet();

sda.Fill (ds,"emp");

this.DataGrid1.DataSource =ds.Tables["emp"];

this.DataGrid1.DataBind ();

然后在page_onload中调用:

if(!this.IsPostBack)

{ this.BindToDataGrid (); }

2. 如果不想写代码就右键-属性生成器,然后设置,此处靠平时多练习,不多说拉

3. 显示上一页,下一页的代码:DataGrid1_PageIndexChanged事件中写:

this.DataGrid1.CurrentPageIndex=e.NewPageIndex;// 取新一页为当前页

this.BindToDataGrid ();

4. 设置第2列不可见:Button1_Click

this.DataGrid1.Columns[1].Visible =false;

this.BindToDataGrid ();

注意:虽然设置了第2列不可见,但是实际它还是存在的,它的序号还是1

5. 鼠标在网格上玄停时网格背景色改变:需要添加一个脚本

在DataGrid1_ItemDataBound事件写 //每一行绑定的时候都会激发ItemDataBound事件

if(e.Item.ItemType==ListItemType.Item||e.Item.ItemType==ListItemType.AlternatingItem)

//先判断选择的是哪个模板判断是否是正常项和交错项

{

e.Item.Attributes.Add("onmouseover","c=this.style.backgroundColor;this.style.backgroundColor='#6699FF'");//设一个变量,取出它当前的背景色,把它设置为一个新的颜色

e.Item.Attributes.Add("onmouseout","this.style.backgroundColor=c");

//使用脚本在用户删除时询问是否要删除

((LinkButton)(e.Item.Cells[6].Controls[0])).Attributes.Add("onclick","return confirm('你确认删除吗?')");

}

6. 单击数据,弹出详细信息的窗口

在属性中添加超级连接列:文本字段和URL字段设置为:EmployeeID,URL格式字符串showDetails.aspx?empID={0}

目标:_blank

新建showDetails页,在Page_Load事件上写:

string empID=Request.QueryString["empID"].ToString();

Response.Write(empID);

Response.Write("<br>");

7. 排序.点击页眉生日显示升序,再点显示降序

在属性的出生日期的排序里面写BirthDate

然后在DataGrid1_SortCommand事件中写:

if(ViewState["Order"]==null)

{ ViewState["Order"]="ASC"; }

else

{

if (ViewState["Order"].ToString()=="ASC")

{ ViewState["Order"]="DESC"; }

else

{ ViewState["Order"]="ASC"; }

}

//数据绑定显示

SqlConnection con=DB.createconnection();;

SqlDataAdapter sda=new SqlDataAdapter();

sda.SelectCommand =new SqlCommand ("select EmployeeID,LastName,FirstName, Title,BirthDate from Employees",con);

DataSet ds=new DataSet();

sda.Fill (ds,"emp");

ds.Tables["emp"].DefaultView.Sort=e.SortExpression+" "+ViewState["Order"].ToString();//默认视图的表达式

this.DataGrid1.DataSource =ds.Tables["emp"].DefaultView;//绑定到表的视图上

this.DataGrid1.DataBind ();

8. 删除信息

删除:在属性生成器-列—按钮列 添加 按钮列 添加删除

在DataGrid1_DeleteCommand事件中写:

string empID=this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString();//把所有主键存在DataKeys中

SqlConnection con=DB.createconnection();

SqlCommand cmd=new SqlCommand("delete from Employees where EmployeeID='"+empID+"'",con);

con.Open();

cmd.ExecuteNonQuery();

this.BindToDataGrid();

9. 修改信息:

编辑:在属性生成器-列—按钮列 添加 按钮列 添加编辑

DataGrid1_EditCommand事件中写:

this.DataGrid1.EditItemIndex=e.Item.ItemIndex;

this.BindToDataGrid();

取消:DataGrid1_CancelCommand事件中写:

this.DataGrid1.EditItemIndex=-1;

this.BindToDataGrid();

更新:DataGrid1_UpdateCommand事件中:

string empID=this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString();

string lastName=((TextBox)(e.Item.Cells [2].Controls[0])).Text; //取单元格里面的控件

Response.Write(empID+"&"+lastName);

10. 验证出生日期的格式:

属性——模板列——选择出生日期——将此列转换为模板列然后在模板里面添加验证控件 设置属性就可以了

CausesValidation:是否触发校验 true:要求所有控件必须通过 false就不出发验证,直接跳过去

11. 打印所选项:button的onclick事件:

遍历网格里面的所有项每次取出一项 使用checkbox定义一个对象 dl本来是行,在行中查找控件,判断它是否被选中

foreach(DataGridItem dl in this.DataGrid1.Items)

{ CheckBox chk=(CheckBox)dl.FindControl ("chkselect");

if(chk.Checked )

{ Response.Write(dl.Cells [1].Text);

Response.Write("<br>");

}

}

SOAP:简单对象访问协议

二十一:购物车的例子哦~~~

1.新建数据库shoppingBus 表petType: petTypeID Varchar 10 petTypeName Varchar 50

表pet: petID Varchar 20 petName Varchar 100 petTypeID Varchar 10

petPrice money petPhoto Varchar 50 petRemark Varchar 50

2.做一个表,做一个样式表控制字体:在HTML里meta name下一行:

<style type="text/css">

TABLE { FONT-SIZE: 12px }

</style>

3.在DataGrid的属性里面添加模板列和超级连接列, 超级连接列的文本字段:petTypeName URl字段:petTypeID

URl格式字符串: showPetByTypeID.aspx?type={0} 目标:_blank;在模板列的itemtemplate中添加一个*,然后在在HTML中把这一列变窄一些,找到<asp:TemplateColumn ItemStyle-Width=10 ItemStyle-HorizontalAlign =Center ItemStyle-VerticalAlign=Top> 设置DataGrid的行高,设置itemstyle font的hight

<ItemTemplate>*….选种表格,然后选择valign属性的top可以让数据顶对齐

5. 在首页里出现数据库中动物的种类:

if(!this.IsPostBack)

{

SqlConnection con=DB.CreateSqlconnection();

con.Open();

SqlCommand cmd=new SqlCommand("select * from petType",con);

SqlDataReader sdr=cmd.ExecuteReader();

this.DataGrid1.DataSource=sdr;

this.DataGrid1.DataBind();

}

6.选择种类后,连接到出现那个种类的详细信息:showPetByTypeID.aspx页面里面

if(!this.IsPostBack )

{

string PetTypeID=Request.QueryString["typeID"].ToString();

SqlConnection con=DB.CreateSqlconnection();

con.Open();

SqlCommand cmd=new SqlCommand("select petTypeName from petType where petTypeID='"+PetTypeID+"'",con);

this.Label1 .Text =Convert.ToString(cmd.ExecuteScalar());

cmd.CommandText="select * from pet where petTypeID='"+PetTypeID+"'";

SqlDataReader sdr=cmd.ExecuteReader();

this.DataGrid1.DataKeyField="petID";

this.DataGrid1 .DataSource=sdr;

this.DataGrid1.DataBind();

}

6. 显示照片

在属性里面:绑定列 页眉文本:宠物照片 数据字段:petPhoto 数据格式设置表达式:<img src=' petPhoto/{0}' weight=60 height=90></img> 在项目新建文件夹petPhoto 放入图片 在绑定列里面还添加:宠物名称,售价,描述;

注意:售价的格式是{0:c}

7. 在宠物详细列表添加一个购买的列:

在属性里面:添加一个按纽列,文本:购买 命令名:AddToBus 然后在设置各列的宽度

购买按纽的处理:DataGrid1_ItemCommand事件中:

if(e.CommandName=="AddToBus")

{

string petID=this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString();//获取主键

if(Session["bus"]==null)//如果会话没有建立,就建立一个集合放数据

{

System.Collections.Hashtable ht=new Hashtable();

ht.Add(petID,1);

Session["bus"]=ht; //把整个集合放在Session里面

// Session.Add("bus",ht);

}

else

{

System.Collections.Hashtable ht=(Hashtable)Session["bus"];//Session返回对象类型,要转换

if(ht[petID]==null)

{

ht[petID]=1;

}

else

{

ht[petID]=(int)ht[petID]+1;

}

Session["bus"]=ht;//更新

}

}

8.查看购物车按纽的代码:Response.Redirect("showbus.aspx");

9.showbus.aspx中page_onload代码:if(!this.IsPostBack)

{

this.DataList1.DataSource=(Hashtable)Session["bus"];//Hashtable是一个集合,可以作为DataSource的数据源

this.DataList1.DataBind();

}

11. 这样DataList1还不能显示数据,在html中编辑模板:

<asp:DataList id="DataList1" runat="server">

<ItemTemplate>

<%# DataBinder.Eval(Container.DataItem,"key") %>:

<%# DataBinder.Eval(Container.DataItem,"value") %>

</ItemTemplate>

</asp:DataList>

12.编辑DataList1,编辑模板——项模板——itemtempalte添加一个textbox——DataBinings——Container——DataItem——格式:value 然后在HTML里删除<%# DataBinder.Eval(Container.DataItem,"value") %>

二十二:用户自定义控件:

1. 新建用户自定义控件,如何取得它的值:在ascs.cs里面写一个属性:

public string txtUserName

{

set //赋值

{ this.Txtusername.Text=value; }

Get //取值

{ return this.Txtusername.Text; }

}

2. 取值按扭的代码:Response.Write(((TextControl)this.FindControl("TC")).txtUserName);

3. 赋值按扭的代码:((TextControl)this.FindControl("TC")).txtUserName="zsw";//FindControl是在一个容器内快速的找到控件的方法

4. <%@ Register TagPrefix="uc1" TagName="TextControl" Src="TextControl.ascx" %>中:

TagPrefix属性:确定用户控件的唯一命名空间,它将是标记中控件名称的前缀;

TagName属性:为用户控件的名称;

Src属性:用户控件的虚拟路径

5. 自定义控件,web控件库在使用时只有一个副本,创建起来比较复杂,而用户控件比较简单,是基于某一个应用程序,每一个应用程序都必须建一个,然后可以直接拖放,不能放在工具箱里面,它会有很多个副本一般都使用。

二十四.在.net中配置应用程序:

配置文件的类型:WebConfig: 应该驻留到服务器上的单个应用程序,每个目录可以有一个

MachineConfig:应该驻留到服务器上的所有应用程序,每个计算机只能有一个,子目录的会覆盖父目录的

WebConfig文件中:1. 对应用程序的所有配置都是放在<configuration>和<configuration>标记里面的

2.<appSettings></appSettings>之间是自定义配置,通常用来设置一些常量

<appSettings>

<add key="con" value="server=.; database=northwind;uid=sa;pwd=;"></add>

</appSettings>

连接时:SqlConnection con=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["con"]);

这样写的好处是:代码一般隐藏在dll动态连接库里,如果更改服务器也可以在类里面改连接对象,但是要重新编译,而这样写直接在config里面改字符串就可以拉

3. <system.web></system.web>之间是关于整个应用程序的设置

4.<location></location>是一个区域标记,一般用来定义对应某一个目录的配置

5. <customErrors mode="RemoteOnly" (加上) defaultRedirect="error.aspx"

/> 只要网站发生什么错误就会跳到这个界面,给用户一个友好的界面

<configuration>

<system.web> <pages busser=”true” //页面是否启动对客户端的缓冲

enableViewState=”false”>

6. 身份验证和授权:可能的模式是 "Windows"、 "Forms"、 "Passport" 和 "None"

一般在局域网上可以用Windows, 互联网上一般用Forms,使用Forms的方法如下:<authentication mode="Forms" />

然后在Internet信息服务里面选择这个站点,在身份证验证方法去掉 匿名访问

Forms标记的属性:


(1)<authentication mode="Forms" >

<forms name="authWeb" loginUrl="login.aspx" protection="All"></forms>

</authentication>

(2)<authorization>//授权

<deny users="?" /> //禁止匿名帐户登陆

(3)使用:连接方法进行验证

if(true)//判断用户是否合法

{ //System.Web.Security.FormsAuthentication.SetAuthCookie(this.TextBox1.Text,false);//把指定的用户名写到数据库里,是否创建永久的Cookie,使用false是临时的,当断开后会话会自动被删除,用来判断下次登陆时是否通过验证

// Response.Redirect(" ");//转向

System.Web.Security.FormsAuthentication.RedirectFromLoginPage(this.TextBox1.Text,this.CheckBox1.Checked);

(4)登出:System.Web.Security.FormsAuthentication.SignOut();//登出

二十五.当系统用户比较少的时候可以用sesson存储用户:

1. 添加一个解决方案: 新建项目——添加到解决方案credential,把它设置为启动项目

2.在Web.config中:<authentication mode="Forms" >

<authentication mode="Forms" >

<forms name="authWeb" loginUrl="login.aspx" protection="All">

<credentials passwordFormat="Clear">

<user name="aaa" password="aaa"/>

<user name="bbb" password="bbb"/>

</credentials>

</forms>

</authentication>

2. <deny users="?" /> //禁止匿名帐户登陆

登陆按钮的代码:if(System.Web.Security.FormsAuthentication.Authenticate(this.TextBox1 .Text,this.TextBox2.Text))//验证用户名,密码是否正确

{

System.Web.Security.FormsAuthentication.SetAuthCookie (this.TextBox1 .Text,false);//将用户名写到Cookie中

Response.Redirect("WebForm1.aspx" );

//System.Web.Security.FormsAuthentication.RedirectFromLoginPage (this.TextBox1 .Text,false);//转回到请求页

}

else

{

Response.Write("用户不合法!");

注意:passwordFormat是密码的格式:还有MD5 SHA1两种格式,MD5的性能比较好,SHA1的安全性比较高

打印出MD5的密码:Response.Write(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(this.Txtpwd.Text,"MD5"));

二十六.缓存:

输出缓存:

在HTML中输入指令:<%@ OutputCache Duration="5" VaryByParam="none" %> VaryByParam表示是否与参数有关

On_load:输出时间:Response.Write(DateTime.Now .ToLongTimeString());刷新时,5秒内不会更新

数据缓存:

在HTML中输入指令 <%@ OutputCache Duration="5" VaryByParam="none"%>

On_load: if(Cache["a"]==null) //如果缓存是空

{

this.Cache.Insert ("a",1000);//此处的1000可以换成DataSet来存储一个数据集

Response.Write("新建缓存");

}

else

{

Response.Write("从缓存中读取:"+Cache["a"].ToString());

}

二十七.打包。

文件——新建项目——安装和部署项目——Web安装项目——添入解决方案——Web应用程序文件夹(填写详细信息)

VirtuDirectory:虚拟目录

右键——添加——项目输出——主输出,内容文件——Release.NET(发布版本)——选中项目名,属性——配置管理器——2个配置都要改成Release ——生成


二十三.一个用用户控件制作网页的例子
table {font-size:12px}

.titl{font-size:12px;color:#ffffff}

.titl:link{font-size:12px;color:#ffffff;text-decoration:none}

.titl:visited{font-size:12px;color:#ffffff;text-decoration:none}

.titl:active{font-size:12px;color:#ffffff;text-decoration:none}

.titl:hove{font-size:12px;color:#ffff00;text-decoration:none}

添加自定义控件时:

<uc1:header id="Header1" runat="server" NewsTypeID="NT1001"></uc1:header></TD>

感谢自己曾经努力过...

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/chenying998179/archive/2008/01/30/2073030.aspx

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics