ASP.NET日常技巧(2)

时间:2008-03-23 03:07:10  类别:asp.net  作者:zouqh

十二. 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


特别推荐

广而告之