日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

ASP.NET网站建设基本常用代码[转载]

發布時間:2024/3/12 asp.net 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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/jRoger/articles/1833610.html

總結

以上是生活随笔為你收集整理的ASP.NET网站建设基本常用代码[转载]的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。