当前位置: 首页 > 编程日记 > 正文

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
MMdd");
当前年月日时分秒 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;
}

转载于:https://www.cnblogs.com/Flynn/archive/2007/08/27/870686.html

相关文章:

C#语言与面向对象技术(6)

本图文主要掌握以下问题&#xff1a; 1.什么是“类型安全”问题&#xff1f; 2.为什么要引入泛型&#xff1f; 3.什么是泛型&#xff1f; 4.泛型是如何实现的&#xff1f; 5.类与类之间存在哪些关系&#xff0c;如何表示&#xff1f;

Xposed: 勾住(Hook) Android应用程序对象的方法,实现AOP

Xposed Xposed能够勾住(Hook) Android应用程序对象的方法&#xff0c;实现AOP&#xff0c;一个简单的例子&#xff1a; public class WebViewHook implements IXposedHookLoadPackage {// handleLoadPackage 会在android加载每一个apk后执行public void handleLoadPackage(Load…

Servlet防止页面被客户端缓存

服务器端的HttpServlet可通过设置特定HTTP响应头来禁止客户端缓存网页&#xff0c;以下示范代码中的response变量引用HttpServletResponse对象&#xff1a; response.addHeader("Pragma","no-cache"); response.setHeader("Cache-Control","…

二进制存储图片

二进制存储图片 如果我们要将一个图片文件二进制于数据库中&#xff0c;那么我们就必须将图片文件转化为二进制数据内容&#xff0c;再将二进制数据存储至数据库中&#xff0c;这是图片存储&#xff08;或是其它文件数据库存储&#xff09;的基本原则。 至于要从数据库中读取图…

《HTML5开发手册》——2.4 初学者“菜谱”:使用address元素提供通信信息

本节书摘来自异步社区《HTML5开发手册》一书中的第2章&#xff0c;第2.4节,作者&#xff1a; 【美】Chuck Hudson , 【英】Tom Leadbetter 更多章节内容可以访问云栖社区“异步社区”公众号查看。 2.4 初学者“菜谱”&#xff1a;使用address元素提供通信信息 规范中将address…

Matlab与线性代数 -- 矩阵的转置

打磨一项技能最需要的就是耐心&#xff0c;我们知道做一件事情不会一蹴而就&#xff0c;需要长时间的积累。关于Matlab的打磨会持续很长的时间&#xff0c;每天学习一个知识点&#xff0c;一年下来就不得了。要有耐心&#xff0c;要有耐心&#xff0c;跟着我们每天花5分钟的时间…

做为程序员对sql进行的性能优化

今天面试&#xff0c;我简历上写了熟悉sql的性能优化&#xff0c;但是今天面试&#xff0c;一时想不起别的&#xff0c;就仅仅说出了一条&#xff0c;在这里再总结一些&#xff0c;完善自己的知识点。 我经常用的数据库是oracle&#xff0c;所以我的sql优化是程序员针对于orac…

asp.NET自定义服务器控件内部细节系列教程四

如大家要转载&#xff0c;请保留本人的版权:/* *Description:asp.NET自定义服务器控件内部细节系列教程*Auther:崇崇-天真的好蓝 *MSN:chongchong2008msn.com *Dates:2007-05-20*Copyright:ChongChong2008 YiChang HuBei China */四 服务器控件相关元数据Attribute 1.设计期A…

《C++游戏编程入门(第4版)》——1.12 习题

本节书摘来自异步社区出版社《C游戏编程入门&#xff08;第4版&#xff09;》一书中的第1章&#xff0c;第1.1节&#xff0c;作者&#xff1a;【美】Michael Dawson&#xff08;道森&#xff09;&#xff0c;更多章节内容可以访问云栖社区“异步社区”公众号查看。 1.12 习题 C…

Matlab与线性代数 -- 单位矩阵

打磨一项技能最需要的就是耐心&#xff0c;我们知道做一件事情不会一蹴而就&#xff0c;需要长时间的积累。关于Matlab的打磨会持续很长的时间&#xff0c;每天学习一个知识点&#xff0c;一年下来就不得了。要有耐心&#xff0c;要有耐心&#xff0c;跟着我们每天花5分钟的时间…

语句覆盖(Statement coverage)

一、语句覆盖(Statement coverage)“语句覆盖”是一个比较弱的测试标准&#xff0c;它的含义是&#xff1a;选择足够的测试用例&#xff0c;使得程序中每个语句至少都能被执行一次。 图6.4是一个被测试的程序&#xff0c;它的源程序…

RSS原理和实现

RSS是在互联网上被广泛采用的内容包装和投递协议。网络用户可以在客户端借助于支持RSS的新闻工具软件&#xff0c;在不打开网站内容页面的情况下&#xff0c;阅读支持RSS输出的网站内容。 1.RSS文件结构 示例&#xff1a; <?xml version"1.0" encoding"gb23…

consul安装配置使用

2019独角兽企业重金招聘Python工程师标准>>> 环境 centos:7.3 docker:1.12.6 kernel:3.10.0-514.6.1.el7.x86_64 consul:0.8.1 server1:10.1.13.221 server2:10.1.13.222 consul的功能 服务发现 健康检查 支持多数据中心 key/value存储 consul的使用场景 docker实例…

Matlab与线性代数 -- 全1矩阵

打磨一项技能最需要的就是耐心&#xff0c;我们知道做一件事情不会一蹴而就&#xff0c;需要长时间的积累。关于Matlab的打磨会持续很长的时间&#xff0c;每天学习一个知识点&#xff0c;一年下来就不得了。要有耐心&#xff0c;要有耐心&#xff0c;跟着我们每天花5分钟的时间…

java 冒泡排序和快速排序 实现

面试的时候经常会遇到面试官让你直接手写排序算法&#xff0c;下面是冒泡排序和快速排序的实现。冒泡排序基本流程就是&#xff0c;自下而上比较相邻的两个元素进行比较&#xff0c;让大的元素往下面沉&#xff0c;较小的往上冒。按照排序规则进行比较&#xff0c;如果是跟排序…

Matlab与线性代数 -- 零矩阵

打磨一项技能最需要的就是耐心&#xff0c;我们知道做一件事情不会一蹴而就&#xff0c;需要长时间的积累。关于Matlab的打磨会持续很长的时间&#xff0c;每天学习一个知识点&#xff0c;一年下来就不得了。要有耐心&#xff0c;要有耐心&#xff0c;跟着我们每天花5分钟的时间…

全球15个顶级技术类博客

1) 生活骇客&#xff08;Lifehacker&#xff09; http://www.lifehacker.com 生活骇客&#xff08;Lifehacker&#xff09;的座右铭表达了它的全部理念&#xff1a;“不要为技术而生活&#xff0c;要为生活而关注技术&#xff01;”这个博客提供了有关于各方各面的“时间节省”…

[ExtJS5学习笔记]第五节 使用fontawesome给你的extjs5应用添加字体图标

本文地址&#xff1a;http://blog.csdn.net/sushengmiyan/article/details/38458411本文作者&#xff1a;sushengmiyan-------------------------------------------------资源链接--------------------------------------------------------FontAwesome glyph编码&#xff1a;…

正则式高人谈解答正则式的心得

条件1&#xff1a; 长度为14个字符 条件2&#xff1a; 其中任意9个位置为数字&#xff0c;并且数字只能是(0,1,3) 条件3&#xff1a; 其余的位置全部为"-"符号 ------------------------------------------ 求一个正则表达式 答案为&#xff1a;^(?!(.*?-){6,})(?…

数据结构与算法--线性表(顺序表)

本图文主要掌握以下问题&#xff1a; 1. 什么是线性表&#xff0c;线性表有哪些操作&#xff1f; 2. 如何利用顺序结构实现线性表&#xff1f;

Myeclipse在启动tomcat的时候的模式改变

在Myeclipse中&#xff0c; windows->preferences->Myeclipse->Servers->Tomcat 然后找到你的相应的Tomcat服务器的版本 当选择Debug mode的时候&#xff0c;当启动tomcat的时候&#xff0c;会进入debug视图 当选择Run mode的时候&#xff0c;启动tomcat的时候&a…

Request.ServerVariables参数集

Request.ServerVariables("Url") 返回服务器地址 Request.ServerVariables("Path_Info") 客户端提供的路径信息 Request.ServerVariables("Appl_Physical_Path") 与应用程序元数据库路径相应的物理路径 Request.ServerVariables("Path_T…

Linux (x86) Exploit 开发系列教程之十一 Off-By-One 漏洞(基于堆)

Off-By-One 漏洞&#xff08;基于堆&#xff09; 译者&#xff1a;飞龙 原文&#xff1a;Off-By-One Vulnerability (Heap Based) 预备条件&#xff1a; Off-By-One 漏洞&#xff08;基于栈&#xff09;理解 glibc mallocVM 配置&#xff1a;Fedora 20&#xff08;x86&#xff…

利用链式存储结构实现线性表

本图文主要介绍了如何利用链式存储结构实现线性表。

自己用的快捷键

win7中 1. Ctrl Shift N —— 创建一个新的文件夹你需要在文件夹窗口中按 Ctrl Shift N 才行&#xff0c;在 Chrome 中是打开隐身窗口的快捷键。2.Win 上/下/左/右 —— 移动当前激活窗口其中&#xff0c;Win 左/右 为移动窗口到屏幕两边&#xff0c;占半屏&#xff0c;Wi…

3月到9月之9月到12月

看看自己这个博客&#xff0c;偶然发现上次的到现在又是半年过去了&#xff0c;这中间发生的太多&#xff0c;可能我天生不爱写东西&#xff0c;呵半年留一次脚印&#xff0c;真不知道我的博客对于博客园来讲算不算资源浪费&#xff01;常看别人的&#xff0c;但自己没写过&…

Java动态代理机制

在Java的动态代理机制中&#xff0c;有两个重要的类。一个是InvocationHandler&#xff0c;另一个是Proxy。InvocationHandler&#xff1a;每一个动态代理类都必须要实现InvocationHandler接口&#xff0c;并且每个代理类的实例都关联到了一个handler&#xff0c;当我们通过代理…

Matlab与线性代数 -- 魔方矩阵

本图文主要介绍了如何利用Matlab实现魔方矩阵。

springMVC 返回类型选择 以及 SpringMVC中model,modelMap.request,session取值顺序

spring mvc处理方法支持如下的返回方式&#xff1a;ModelAndView, Model, ModelMap, Map,View, String, void。下面将对具体的一一进行说明&#xff1a; ModelAndView Java代码 RequestMapping("/show1") public ModelAndView show1(HttpServletRequest request, …