1.Asp.Net中几种相似的标记符号: <%=...%> <%#... %> <% %> <%@ %> 解释及用法
答: <%#... %>: 是在绑定控件DataBind()方法执行时被执行,用于数据绑定
如: <%# Container.DataItem("tit") %>
<%= %>: 在程序执行时被调用,可以显示后台变量值
如:
*.aspx中: <%= aaa %>
*.cs中: protected string aaa="姓名";
<% %>: 内联代码块里面可以在页面文件*.aspx或*.ascx文件里面嵌入后台代码
如:
<%
for(int i=0;i<100;i++)
{
Reaponse.Write(i.ToString());
}
%>
<%@ %>是在*.aspx页面前台代码导入命名空间或指定后台文件路径等信息,
如:
<%@ Import namespace="System.Data"%>
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs"
AutoEventWireup="false" Inherits="WebApplication5.WebForm1" %>
2.控件接收哪些类型数据?
答:接收Bind的控件,一般有DropDownList,DataList,DataGrid,ListBox这些集合性质的控件,而被捆绑 的主要是ArrayList(数组),Hashtable(哈稀表),DataView(数据视图),DataReader这四个,以后我们就可以 对号入座,不会出现DataTable被捆绑的错误了:)
3.DataBind,获得的数据,系统会将其默认为String,怎样转化为其它的类型?
DataBinder.Eval(Container.DataItem,"转换的类型","格式")
最后一个"格式"是可选的,一般不用去管他,Container.DataItem是捆绑的数据项,"转换类型"指的是 Integer,String,Boolean这一类东西.
4.主要命名空间:
<% @ Import Namespace="System.Data" %> 处理数据时用到
<% @ Import Namespace="System.Data.ADO" % > 使用ADO.net ; 时用到
<% @ Import Namespace="System.Data.SQL" %> SQL Server 数据库专用
<% @ Import Namespace="System.Data.XML" %> 不用看处理XML用到
<% @ Import Namespace="System.IO" %> 处理文件时用到
<% @ Import Namespace="System.Web.Util" %> 发邮件时大家会用到
<% @ Import Namespace="System.Text" %> 文本编码时用到
5.Connections(SQLConection 或者 ADOConnection)的常用属性和方法:
| ConnectionString 取得或设置连结数据库的语句
| ConnectionTimeout 取得或设置连结数据库的最长时间,也是就超时时间
| DataBase 取得或设置在数据库服务器上要打开的数据库名
| DataSource 取得或设置DSN,大家不会陌生吧:)
| Password 取得或设置密码
| UserID 取得或设置登陆名
| State 取得目前联结的状态
| Open() 打开联结
| Close() 关闭联结
| Clone() 克隆一个联结。(呵呵,绵羊可以Connection我也可以)
示例:
SQLConnection myConnection = new SQLConnection();
myConnection.DataSource = "mySQLServer";
myConnection.Password = "";
myConnection.UserID = "sa";
myConnection.ConnectionTimeout = 30;
myConnection.Open();
myConnection.Database = "northwind";
myConnection.IsolationLevel = IsolationLevel.ReadCommitted
6.Command常用的方法和属性
| ActiveConnection 取得或设置联结Connections
| CommandText 执行的SQL语句或储存过程(StoredProcedure)名
| CommandTimeout 执行的最长时间
| CommandType Command操作的类型(StoredProcedure,Text,TableDirect)三种,默认Text
| Parameters 操作储存过程时使用
| Execute() 执行SQL语句或储存过程
| ExecuteNonQuery() 同上,区别在于不返回记录集
| Clone() 克隆Command
示例:
string mySelectQuery = "SELECT * FROM Categories ORDER BY CategoryID";
stringmyConnectString="userid=sa;password=;database=northwind;server=mySQLServer";
SQLCommand myCommand = new SQLCommand(mySelectQuery);
myCommand.ActiveConnection = new SQLConnection(myConnectString);
myCommand.CommandTimeout = 15;
myCommand.CommandType = CommandType.Text;< /FONT >
7.打开和关闭数据库两种方法:
1.MyConnection.Open(); //打开联结
MyConnection.Close();
2.MyCommand.ActiveConnection.Open();
MyCommand.ActiveConnection.Close()
8.使用DataSet,在数据库中增加、修改、删除一个数据
a.添加数据
DataRow dr=MyDataSet.Tables["UserList"].NewRow();
dr["UserName"] = "周讯";
dr["ReMark"] = "100";
dr["Comment"] = "漂亮MM";
MyDataSet.Tables.Rows.Add(dr);
b.修改数据
MyDataSet.Tables["UserList"].Rows[0]["UserName"]="飞刀大哥";
c.删除数据
MyDataSet.Tables["UserList"],Rows[0].Delete();
d.恢复数据
if(MyDataSet.HasErrors)
{
MyDataSet.RejectChanges();
}
e.探测DataSet是否有改动
if(MyDataSet.HasChanges)
{
//保存代码
}else{
//因为没有变化,所以不用保存,以节省时间
}
f.更新数据库
MyComm.Update(MyDataSet); //更新数据库中所有的表
MyComm.Update(MyDataSet,"UserList"); //更新某个表
9.DataGrid实现分页功能
AllowPaging="True" //是指允许分页,这个是最主要的。有了它,我们才能分页。
PageSize="5" //是指定每页显示的记录数,如果不写,就会默认为10条。
PagerStyle-HorizontalAlign="Right" //是指定分面显示的定位,默认是Left
PagerStyle-NextPageText="下一页" //把<>改为上一页和下一页字符串
PagerStyle-PrevPageText="上一页"
PagerStyle-Mode="NumericPages" //把<>改为123数字显示
10.显示一共有多少页,并且报告当前为第几页
当前页是:<font color=red><%=DataGrid1.CurrentPageIndex+1%></font><br>
总页数是:<font color=red><%=DataGrid1.PageCount%></font><br>
11.个性化分页
程序员大本营之"亲密接触ASP.Net(14)"有完整代码
12.要将页面重置为有效的状态
IValidator val;
foreach(val in Validators)
{
Val.IsValid = true;
}
13.重新执行整个验证序列
IValidator val;
foreach(val in Validators)
{
Val.Validate();
}
14.禁用客户端验证
<%@ Page Language="c#" clienttarget=downlevel %>
15.Repeater、DataList和DataGrid控件用途"
这些控件可以简化几种常见的 Web 应用程序方案,包括报表、购物车、产品列表、查询
结果和导航菜单。 Repeater是唯一允许在其模板中存在 HTML片段的控件.
16.Server.Execute("another.aspx")和Server.Transfer("another.aspx")区别:
Execute是从当前页面转移到指定页面,并将执行返回到当前页面
Transfer是将执行完全转移到指定页面
17.XML文件中可以自己存有架构,也可以存在于*.xsl文件中,但必须通过xmlns属性在xml文档的根节点中指定该信息,如下所示:
<rootelement xmlns="x-schema:scheduledSchema.xsl">
18.XML文件的读取
FileStream myfs=new Filestream(Server.MapPath("xmldtagrid.xml"),FileMode.Open,FileAccess.Read);
StreamReader myreader=new StreamReader(myfs);
DataSet myds=new DataSet();
myds.ReadXml(myreader);
19.正则表达式 控件RegularExpressionValidator
符号 含义
^ 指定检查开始处
$ 指定检查结束处
[] 检查输入的值是否与方括弧中的字符之一相匹配
/W 允许输入任何值
/d{} "/d"指定输入的值是一个数字,{}表示已指定数据类型的出现次数
+ 表明一个或多个元素将被添加到正在检查的表达式
示例:电子邮件格式(具有@号,且以.com/.net/.org/.edu结尾)
validationexpression="^[/w-]+@[/w-]+/.(com|net|org|edu)$"
20.DataGrid控件中数据操作重要语句:
属性:DataKeyField="userid" //设userid为表的主键,无法将该字段的值更新到数据库,最好设表的主键为DataGrid的主键
SqlCommand.Parameters["@userid"].Value=dg.DataKeys[(int)e.Item.ItemIndex]; //检索所要更新的行的主键(将当前选定的行的 主键值赋给命令的一个参)数
SqlCommand.Parameters["@fname"].Value=((TextBox)e.Item.Cells[2].Controls[0]).Text; //为参数赋予已修改的行值
21.自定义控件:
a.用户控件(ASP创建页面一样)
(I). 创建页面,拖入控件,设置属性/方法. <% @Control Language="C#" Debug="True" %>中的@Control指令来定义此页 将包含控件代码
(II) 保存为*.ascx文件,如a.ascx.
(III).使用: 头<%@Register Tagprefix="MyFirstControl" TagName="MyLbl" Src="a.axcs" %>
//Tagprefix为控件的前缀,像ASP:TextBox中的ASP
//TagName用于指定自定义控件的名称
//Src指定控件文件源
身体:<MyFirstControl:MyLbl runat="Server" id="AllMine" MyText="成功了" />
b.使用C#创建自定义控件
(I). 创建纯代码文件,继承基类Control,并保存为*.cs,如a.cs.
(II).将代码编译生成程序集: csc /t:library /r:System.dll,System.Web.Dll a.cs
//library告诉C#编译器生成程序集
// /r:System.dll System.Web.Dll告诉C#编译器引用指定的程序集
(III).将生成dll文件放在bin目录中
(IV).使用: <% @Register TagPrefix="Mine" Namespace="MyOwnControls" Assembly="a" %>
22.复合控件注意事项:
public class MyCompositin:Control,INamingContainer //INamingContainer:如果在页面上有多个此控件实例,则此结口可以给每 {} //个实例有唯一标志
this.EnsureChildControls();//表示将复合控件的子控件都呈现到页面上,此方法检查服务器控件是否包含子控件
CreateChildControls
23.Button/LinkButton/ImageButton/HyperLink什么时候用?
1.Button和ImageButton用于将数据传递回服务器.
2.Hyperlink用于在页面之间导航
3.LinkButton用于将数据保存到服务器或访问服务器上的数据
24.跟踪调试
跟踪:
1.页级别跟踪: 在页的开头包括如下的页指令<%@ Page Trace="True" TraceMode="SortByCategory/SortByTime" %>
自定义消息:
Trace.Write("这里为要显示的字符串");
Trace.Warn("这里为要显示的字符串"); //与Trace.Write相同,只是字体为红色
检查是否使用了跟踪
例句: if(Trace.IsEnabled) { Trace.Warn("已启用跟踪")}
2.应用程序级别跟踪: 在Web.config文件的<System.Web>节中 <trace enabled="true" pageOutput="true"/>
25.设置缓存:
1.输出缓存:
I.页面设置: 将 <%@ OutputCache Duration="120" VaryByParam="none" %> 加在需要缓存页的开头
注释:在请求该页的后两分钟之内,输出内容不变
II.编程方式设置:
主要使用类System.Web.HttpCachePolicy类下的方法
(1). Response.Cache.SetExpires(DateTime.Now.AddSeconds(120)); //在此方法中必须指定到期时间,如本语 //句为两分钟
(2). Response.Cache.SetExpires(DateTime.Now.AddSeconds(120));
Response.Cache.SetSlidingExpiration(true); //"可调到期",主要用于那些开始访问量大,但随后访问 //量平衡的情况
功能:第一句设置缓存到期时间,第二行打开 sliding expiration(可调到期).
2.数据缓存:
(1).DataView mySource; (2).给mySource赋值;
(3).Cache["myCache"]=mySource; (4).mySource=(DataView)Cache["myCache"]
26.部署: 直接复制到产品服务器即可 复制语句: XCOPY <source_path> <destination_path> //XOPY只接受物理路径,不接受虚拟路径
26.自定义分页按钮
1.
protected void ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
System.Web.UI.WebControls.ListItemType elemType = e.Item.ItemType;
if (elemType == System.Web.UI.WebControls.ListItemType.Pager)
{
TableCell pager = (TableCell) e.Item.Controls[0];
for (int i=0; i<pager.Controls.Count; i+=2)
{
Object o = pager.Controls[i];
if (o is LinkButton)
{
LinkButton h = (LinkButton) o;
h.Text = " " + h.Text + " ";
}
else
{
Label l = (Label) o;
l.Text = String.Format("[第{0}页]", l.Text);
}
}
}
}
2. 引用:zhangzs8896(小二)
private void MyDataGrid_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
ListItemType lit_item=e.Item.ItemType;
TableCell tc_item=(TableCell)e.Item.Controls[0];
if (lit_item==ListItemType.Pager)
{
for (int i=0;i<tc_item.Controls.Count;i+=2)
{
object obj_item=tc_item.Controls[i];
if (obj_item is LinkButton)
{
LinkButton lbn_item=(LinkButton)obj_item;
lbn_item.Text=lbn_item.Text;
lbn_item.Font.Size=10;
lbn_item.ForeColor=Color.FromName("#666666");
lbn_item.Attributes.Add ("onmouseover","currentcolor=this.style.color;this.style.color='#14AC05'");
lbn_item.Attributes.Add("onmouseout","this.style.color=currentcolor");
}
else
{
Label lbl_item=(Label)obj_item;
lbl_item.ForeColor=Color.Blue;
lbl_item.Font.Bold=true;
lbl_item.Font.Underline=true;
lbl_item.Text="<font color='#666666'>" + lbl_item.Text + "</font>";
lbl_item.Font.Size=10;
}
}
}
}
[以下为转载]
27、DateTime 数字型
System.DateTime currentTime=new System.DateTime();
1.1 取当前年月日时分秒
currentTime=System.DateTime.Now;
1.2 取当前年
int 年=currentTime.Year;
1.3 取当前月
int 月=currentTime.Month;
1.4 取当前日
int 日=currentTime.Day;
1.5 取当前时
int 时=currentTime.Hour;
1.6 取当前分
int 分=currentTime.Minute;
1.7 取当前秒
int 秒=currentTime.Second;
1.8 取当前毫秒
int 毫秒=currentTime.Millisecond;
(变量可用中文)
28、Int32.Parse(变量) Int32.Parse("常量")
字符型转换 转为32位数字型
29、 变量.ToString()
字符型转换 转为字符串
12345.ToString("n"); //生成 12,345.00
12345.ToString("C"); //生成 ¥12,345.00
12345.ToString("e"); //生成 1.234500e+004
12345.ToString("f4"); //生成 12345.0000
12345.ToString("x"); //生成 3039 (16进制)
12345.ToString("p"); //生成 1,234,500.00%
30、变量.Length 数字型
取字串长度:
如: string str="中国";
int Len = str.Length ; //Len是自定义变量, str是求测的字串的变量名
31、System.Text.Encoding.Default.GetBytes(变量)
字码转换 转为比特码
如:byte[] bytStr = System.Text.Encoding.Default.GetBytes(str);
然后可得到比特长度:
len = bytStr.Length;
32、System.Text.StringBuilder("")
字符串相加,(+号是不是也一样?)
如:System.Text.StringBuilder sb = new System.Text.StringBuilder("");
sb.Append("中华");
sb.Append("人民");
sb.Append("共和国");
33、变量.Substring(参数1,参数2);
截取字串的一部分,参数1为左起始位数,参数2为截取几位。
如:string s1 = str.Substring(0,2);
34、String user_IP=Request.ServerVariables["REMOTE_ADDR"].ToString();
取远程用户IP地址
35、穿过代理服务器取远程用户真实IP地址:
if(Request.ServerVariables["HTTP_VIA"]!=null){
string user_IP=Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}else{
string user_IP=Request.ServerVariables["REMOTE_ADDR"].ToString();
}
36、 Session["变量"];
存取Session值;
如,赋值: Session["username"]="小布什";
取值: Object objName=Session["username"];
String strName=objName.ToString();
清空: Session.RemoveAll();
37、String str=Request.QueryString["变量"];
用超链接传送变量。
如在任一页中建超链接:<a href=Edit.aspx?fbid=23>点击</a>
在Edit.aspx页中取值:String str=Request.QueryString["fdid"];
38、DOC对象.CreateElement("新建节点名");
创建XML文档新节点
39、父节点.AppendChild(子节点);
将新建的子节点加到XML文档父节点下
40、 父节点.RemoveChild(节点);
删除节点
41、Response
Response.Write("字串");
Response.Write(变量);
向页面输出。
Response.Redirect("URL地址");
跳转到URL指定的页面
42、char.IsWhiteSpce(字串变量,位数)——逻辑型
查指定位置是否空字符;
如:
string str="中国 人民";
Response.Write(char.IsWhiteSpace(str,2)); //结果为:True, 第一个字符是0位,2是第三个字符。
43、char.IsPunctuation('字符') --逻辑型
查字符是否是标点符号
如:Response.Write(char.IsPunctuation('A')); //返回:False
44、(int)'字符'
把字符转为数字,查代码点,注意是单引号。
如:
Response.Write((int)'中'); //结果为中字的代码:20013
45、(char)代码
把数字转为字符,查代码代表的字符。
如:
Response.Write((char)22269); //返回“国”字。
46、 Trim()
清除字串前后空格
47 、字串变量.Replace("子字串","替换为")
字串替换
如:
string str="中国";
str=str.Replace("国","央"); //将国字换为央字
Response.Write(str); //输出结果为“中央”
再如:(这个非常实用)
string str="这是<script>脚本";
str=str.Replace("<","<font><</font>"); //将左尖括号替换为<font> 与 < 与 </font> (或换为<,但估计经XML存诸后,再提出仍会还原)
Response.Write(str); //显示为:“这是<script>脚本”
如果不替换,<script>将不显示,如果是一段脚本,将运行;而替换后,脚本将不运行。
这段代码的价值在于:你可以让一个文本中的所有HTML标签失效,全部显示出来,保护你的具有交互性的站点。
具体实现:将你的表单提交按钮脚本加上下面代码:
string strSubmit=label1.Text; //label1是你让用户提交数据的控件ID。
strSubmit=strSubmit.Replace("<","<font><</font>");
然后保存或输出strSubmit。
用此方法还可以简单实现UBB代码。
48、Math.Max(i,j)
取i与j中的最大值
如 int x=Math.Max(5,10); // x将取值 10
49.日期格式
System.Globalization.DateTimeFormatInfo myDTFI = new System.Globalization.CultureInfo( "en-US", false ).DateTimeFormat;//中国用zh-cn
DateTime myDT =System.DateTime.Now;
Response.Write(myDT.ToString("d",myDTFI));
Response.Write(myDT.ToString("D",myDTFI));
Response.Write("<br>");
Response.Write(myDT.ToString("f",myDTFI));
Response.Write(myDT.ToString("F",myDTFI));
Response.Write("<br>");
Response.Write(myDT.ToString("g",myDTFI));
Response.Write(myDT.ToString("G",myDTFI));
Response.Write("<br>");
Response.Write(myDT.ToString("m",myDTFI));
Response.Write(myDT.ToString("M",myDTFI));
Response.Write("<br>");
Response.Write(myDT.ToString("r",myDTFI));
Response.Write(myDT.ToString("R",myDTFI));
Response.Write("<br>");
Response.Write(myDT.ToString("s",myDTFI));
//Response.Write(myDT.ToString("S",myDTFI));
Response.Write("<br>");
Response.Write(myDT.ToString("t",myDTFI));
Response.Write(myDT.ToString("T",myDTFI));
Response.Write("<br>");
Response.Write(myDT.ToString("u",myDTFI));
Response.Write(myDT.ToString("U",myDTFI));
Response.Write("<br>");
Response.Write(myDT.ToString("y",myDTFI));
Response.Write(myDT.ToString("Y",myDTFI));