ASP.NET网站建设基本常用代码

1.为按钮添加确认对话框
Button.Attributes.Add("onclick","return confirm('确认?')");
Button.Attributes.Add("onclick","if(confirm('确定?')){return true;}else{return false;}")
2.表格超连接列传递参数
<asp:HyperLinkColumn Target="_blank" headertext="ID号" DataTextField="id" NavigateUrl="aaa.aspx?id='<%# DataBinder.Eval(Container.DataItem, "数据字段1")%>'&name='<%# DataBinder.Eval(Container.DataItem, "数据字段2")%>'/>
3.表格点击改变颜色
if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem)
{
e.Item.Attributes.Add("onclick","this.style.backgroundColor='#99cc00';this.style.color='buttontext';this.style.cursor='default';");
}
4.清空Cookie
Cookie.Expires=[DateTime];
Response.Cookies("UserName").Expires = 0;
5.Panel 横向滚动,纵向自动扩展
<asp:panel style="overflow-x:scroll;overflow-y:auto;"></asp:panel>
6.数字格式化
<%#Container.DataItem("price")%> 结果:500.0000格式化:500.00
<%#Container.DataItem("price","{0:¥#,##0.00}")%>
int i=123456;
string s=i.ToString("###,###.00");
7.日期格式化
<%# DataBinder.Eval(Container.DataItem,"Date")%> 结果:2004-8-11 19:44:28 格式化:2004-8-11
<%# DataBinder.Eval(Container.DataItem,"Date","{0:yyyy-M-d}")%>
8.时间格式化
string aa=DateTime.Now.ToString("yyyy年MM月dd日");
当前年月日时分秒 currentTime=System.DateTime.Now;
当前年 int 年= DateTime.Now.Year;
当前毫秒 int 毫秒= DateTime.Now.Millisecond;
9.自定义分页代码
public static int pageCount; //总页面数
public static int curPageIndex=1; //当前页面   
if(ccDataGrid.CurrentPageIndex<(ccDataGrid.PageCount - 1))
{//下一页
  ccDataGrid.CurrentPageIndex += 1;
  curPageIndex+=1;
}
bind(); // ccDataGrid数据绑定函数
if(ccDataGrid.CurrentPageIndex>0)
{ //上一页
  ccDataGrid.CurrentPageIndex += 1;
  curPageIndex-=1;
}
bind(); // ccDataGrid数据绑定函数
int a=int.Parse(JumpPage.Value.Trim());//JumpPage.Value.Trim()为跳转值
if(a<DataGrid1.PageCount)
{ //直接页面跳转
  this.ccDataGrid.CurrentPageIndex=a;
}
bind(); // ccDataGrid数据绑定函数
10.变量.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%
11.客户端验证控件
//验证空值
<asp:requiredfieldvalidator id="valUsername" runat="server" controltovalidate="txtUsername" display="None" errormessage="请输入用户名 !!"></asp:requiredfieldvalidator>
//验证网址
<asp:regularexpressionvalidator id="rev" runat="server" ErrorMessage="公司网址不合法[要有http://] !" Display="None" ControlToValidate="txtCPWebsite" ValidationExpression="http://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?"></asp:regularexpressionvalidator>
//验证邮箱
<asp:RequiredFieldValidator id="rfv" runat="server" ControlToValidate="txtCPEmail" Display="None" ErrorMessage="请输入电子邮箱 !!"></asp:RequiredFieldValidator>
//验证邮编
<asp:regularexpressionvalidator id="rev5" runat="server" ErrorMessage="邮政编码不合法 !" Display="None" ControlToValidate="txtCPPostCode" ValidationExpression="\d{6}"></asp:regularexpressionvalidator>
//显示错误信息
<asp:validationsummary id="vs" runat="server" ShowSummary="False" ShowMessageBox="True"></asp:validationsummary>
12.DataBinding绑定表达式
1) 普通的绑定表达式
<%# DataBinder.Eval(Container.DataItem, "ContactName") %>
2) 文本+绑定表达式
<asp:Label id=lblDate runat="server" Text='<%# "[" + DataBinder.Eval(Container, "DataItem.NewsCreatedate") + "]" %>' ForeColor="Red"></asp:Label>
3) 同时带有显示格式的绑定表达式
<%# DataBinder.Eval(Container,"DataItem.USActiveDate","{0:yyyy-MM-dd}") %>
4) 结合绑定表达式和模态框
<A href='<%# ShowModalWin(Convert.ToString(DataBinder.Eval(Container.DataItem, "PictureImage")),Convert.ToString(DataBinder.Eval(Container.DataItem, "DetailID")),Convert.ToString(DataBinder.Eval(Container.DataItem, "PictureID")))%>'>
其中:后台代码文件中ShowModalWin()方法的定义如下:
protected string ShowModalWin(string PictureImage,string DetailID,string PictureID)
{
return " window.showModalDialog(\"Customers/ShowPictureInfo.aspx?pid="+PictureImage+"&did="+DetailID+"&id="+PictureID+"\",\"\",\"dialogHeight:320px;dialogWidth:480px;center:yes;help:no;status:no;scroll:no\");";
}
或者将参数提取出来单独定义成一变量:
const string WINDOWPARAMSTRING="dialogWidth:540px;dialogHeight:420px;help:0;status:0;resizeable:1;scroll:no";
Page.RegisterStartupScript("functionscript","<script language='javascript'>window.showModalDialog('EditUserService.aspx?URID="+iURID+"','','"+WINDOWPARAMSTRING+"')</script>");
13.html字符转换的两个函数
public string Encode(string str)
{
str=str.Replace("&","&amp;");
str=str.Replace("'","''");
str=str.Replace("\"","&quot;");
str=str.Replace(" ","&nbsp;");
str=str.Replace("<","&lt;");
str=str.Replace(">","&gt;");
str=str.Replace("\n","<br>");
return str;
}
public string Decode(string str)
{
str=str.Replace("\n","<br>");
str=str.Replace("&gt;",">");
str=str.Replace("&lt;","<");
str=str.Replace("&nbsp;"," ");
str=str.Replace("&quot;","\"");
return str;
}
14.产生62位内任意数字大小写字母的随机数
private static char[] constant=
{
'0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
};
public static string GenerateRandom(int Length)
{
System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62);
Random rd= new Random();
for(int i=0;i<Length;i++)
{
newRandom.Append(constant[rd.Next(62)]);
}
return newRandom.ToString();
}
//调用
string str=GenerateRandom(6);//参数表示需要产生随机数的数目
15.图像加入版权信息
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
private void AddTextToImg(string fileName,string text)
{
if(!File.Exists(MapPath(fileName)))
{
throw new FileNotFoundException("The file don't exist!");
}
if( text == string.Empty )
{
return;
}
//还需要判断文件类型是否为图像类型
System.Drawing.Image image = System.Drawing.Image.FromFile(MapPath(fileName));
Bitmap bitmap = new Bitmap(image,image.Width,image.Height);
Graphics g = Graphics.FromImage(bitmap);
float fontSize = 12.0f; //字体大小
float textWidth = text.Length*fontSize; //文本的长度
//下面定义一个矩形区域,以后在这个矩形里画上白底黑字
float rectX = 0;
float rectY = 0;
float rectWidth = text.Length*(fontSize+8);
float rectHeight = fontSize+8;
//声明矩形域
RectangleF textArea = new RectangleF(rectX,rectY,rectWidth,rectHeight);
Font font = new Font("宋体",fontSize); //定义字体
Brush whiteBrush = new SolidBrush(Color.White); //白笔刷,画文字用
Brush blackBrush = new SolidBrush(Color.Black); //黑笔刷,画背景用
g.FillRectangle(blackBrush,rectX,rectY,rectWidth,rectHeight);
g.DrawString(text,font,whiteBrush,textArea);
MemoryStream ms = new MemoryStream( );
//保存为Jpg类型
bitmap.Save(ms,ImageFormat.Jpeg);
//输出处理后的图像,这里为了演示方便,我将图片显示在页面中了
Response.Clear();
Response.ContentType = "image/jpeg";
Response.BinaryWrite( ms.ToArray() );
g.Dispose();
bitmap.Dispose();
image.Dispose();
}
//调用
AddTextToImg("me.jpg","Family.Man");
16.常用正则表达式集锦
"^\\d+$"  //非负整数(正整数 + 0)
"^[0-9]*[1-9][0-9]*$"  //正整数
"^((-\\d+)|(0+))$"  //非正整数(负整数 + 0)
"^-[0-9]*[1-9][0-9]*$"  //负整数
"^-?\\d+$"    //整数
"^\\d+(\\.\\d+)?$"  //非负浮点数(正浮点数 + 0)
"^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$"  //正浮点数
"^((-\\d+(\\.\\d+)?)|(0+(\\.0+)?))$"  //非正浮点数(负浮点数 + 0)
"^(-(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*)))$"  //负浮点数
"^(-?\\d+)(\\.\\d+)?$"  //浮点数
"^[A-Za-z]+$"  //由26个英文字母组成的字符串
"^[A-Z]+$"  //由26个英文字母的大写组成的字符串
"^[a-z]+$"  //由26个英文字母的小写组成的字符串
"^[A-Za-z0-9]+$"  //由数字和26个英文字母组成的字符串
"^\\w+$"  //由数字、26个英文字母或者下划线组成的字符串
"^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$"    //email地址
"^[a-zA-z]+://(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$"  //url
17.绑定在DataList中的DropDownList
private void dlistOrder_EditCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e)
{
//绑定订单状态
for(int i=0;i<((DropDownList)dlistOrder.Items[e.Item.ItemIndex].FindControl("ddlFlag")).Items.Count;i++)
{
if(((DropDownList)dlistOrder.Items[e.Item.ItemIndex].FindControl("ddlFlag")).Items[i].Value == dv.Table.Rows[0]["OrStatus"].ToString())
{
((DropDownList)dlistOrder.Items[e.Item.ItemIndex].FindControl("ddlFlag")).Items[i].Selected = true;
}
}
}
//另一种绑定方式,绑定送货方式
DataView shipType = OrderSO.GetShipTypeList();
DropDownList ddlShipType = (DropDownList)dlistOrder.Items[e.Item.ItemIndex].FindControl("ddlShipType");
ddlShipType.DataSource = shipType;
ddlShipType.DataTextField = "StName";
ddlShipType.DataValueField = "StId";
ddlShipType.DataBind();
ddlShipType.SelectedIndex = ddlShipType.Items.IndexOf(ddlShipType.Items.FindByValue(dv.Table.Rows[0]["OrShipType"].ToString()));
18.验证用户名必须以字母打头且不能含有中文
String sUsername = txtUsername.Text.Trim();
if(!Regex.IsMatch(sUsername, "^[A-Za-z].*"))
{
Utility.MessageBox(this,"nameFormatError","用户名要以字母开头, 且不要用中文名称 !!");
return;
}