ASPNET程序中常用的三十三種代碼_第1頁
ASPNET程序中常用的三十三種代碼_第2頁
ASPNET程序中常用的三十三種代碼_第3頁
ASPNET程序中常用的三十三種代碼_第4頁
ASPNET程序中常用的三十三種代碼_第5頁
已閱讀5頁,還剩15頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

1、ASP.NET程序中常用的三十三種代碼(收集)1打開新的窗口并傳送參數:12為按鈕添加對話框23刪除表格選定記錄24刪除表格記錄警告25點擊表格行鏈接另一頁36表格超連接列傳遞參數37表格點擊改變顏色48關于日期格式49獲取錯誤信息并到指定頁面410清空Cookie511自定義異常處理512Panel 橫向滾動,縱向自動擴展913回車轉換成Tab914DataGrid超級連接列915DataGrid行隨鼠標變色916模板列1017數字格式化1118日期格式化1119如何設定全局變量1220怎樣作到HyperLinkColumn生成的連接后,點擊連接,打開新窗口?1221讀取DataGrid控件

2、TextBox值1323自動模板列計算:在錄入數量及單價的時候自動算出金額1324datagrid選定比較底下的行時,為什么總是刷新一下,然后就滾動到了最上面,剛才選定的行因屏幕的關系就看不到了。1425在Datagrid中修改數據,當點擊編輯鍵時,數據出現在文本框中,怎么控制文本框的大小 ?1426對話框1527將時間格式化:string aa=DateTime.Now.ToString("yyyy年MM月dd日");1528自定義分頁代碼:1629DataGrid使用:1630當文件在不同目錄下,需要獲取數據庫連接字符串(如果連接字符串放在Web.config,然后在G

3、lobal.asax中初始化)1831變量.ToString()1832變量.Substring(參數1,參數2);1933在自己的網站上登陸其他網站:(如果你的頁面是通過嵌套方式的話,因為一個頁面只能有一個FORM,這時可以導向另外一個頁面再提交登陸信息)191打開新的窗口并傳送參數: 傳送參數:response.write("scriptwindow.open(*.aspx?id="+this.DropDownList1.SelectIndex+"&id1="+.+")/script"); /response.write(

4、"");接收參數:string a = Request.QueryString("id");string b = Request.QueryString("id1");2為按鈕添加對話框Button1.Attributes.Add("onclick","return confirm(確認?)");button.attributes.add("onclick","if(confirm(are you sure.?)return true;elsereturn fals

5、e;")3刪除表格選定記錄int intEmpID = (int)MyDataGrid.DataKeyse.Item.ItemIndex; /e參見下一例string deleteCmd = "DELETE from Employee where emp_id = " + intEmpID.ToString()4刪除表格記錄警告private void DataGrid_ItemCreated(Object sender,DataGridItemEventArgs e)switch(e.Item.ItemType)case ListItemType.Item :c

6、ase ListItemType.AlternatingItem :case ListItemType.EditItem:TableCell myTableCell;myTableCell = e.Item.Cells14;LinkButton myDeleteButton ;myDeleteButton = (LinkButton)myTableCell.Controls0;myDeleteButton.Attributes.Add("onclick","return confirm(您是否確定要刪除這條信息);");break;default:bre

7、ak;5點擊表格行鏈接另一頁private void grdCustomer_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)/點擊表格打開if (e.Item.ItemType = ListItemType.Item | e.Item.ItemType = ListItemType.AlternatingItem)e.Item.Attributes.Add("onclick","window.open(Default.aspx?id=" + e

8、.Item.Cells0.Text + ");");雙擊表格連接到另一頁在itemDataBind事件中if(e.Item.ItemType = ListItemType.Item | e.Item.ItemType = ListItemType.AlternatingItem)string OrderItemID =e.item.cells1.Text;.e.item.Attributes.Add("ondblclick", "location.href=./ShippedGrid.aspx?id=" + OrderItemID +

9、 "");雙擊表格打開新一頁if(e.Item.ItemType = ListItemType.Item | e.Item.ItemType = ListItemType.AlternatingItem)string OrderItemID =e.item.cells1.Text;.e.item.Attributes.Add("ondblclick", "open(./ShippedGrid.aspx?id=" + OrderItemID + ")");6表格超連接列傳遞參數asp:HyperLinkColumn

10、Target="_blank" headertext="ID號" DataTextField="id" NavigateUrl="aaa.aspx?id=%# DataBinder.Eval(Container.DataItem, "數據字段1")% & name=%# DataBinder.Eval(Container.DataItem, "數據字段2")% /7表格點擊改變顏色if (e.Item.ItemType = ListItemType.Item |e.Item.I

11、temType = ListItemType.AlternatingItem) e.Item.Attributes.Add("onclick","this.style.backgroundColor=#99cc00; this.style.color=buttontext;this.style.cursor=default;"); 寫在DataGrid的_ItemDataBound里if (e.Item.ItemType = ListItemType.Item |e.Item.ItemType = ListItemType.AlternatingItem

12、)e.Item.Attributes.Add("onmouseover","this.style.backgroundColor=#99cc00;this.style.color=buttontext;this.style.cursor=default;");e.Item.Attributes.Add("onmouseout","this.style.backgroundColor=;this.style.color=;");8關于日期格式日期格式設定DataFormatString="0:yyyy-MM

13、-dd"我覺得應該在itembound事件中e.items.cell"你的列".text=DateTime.Parse(e.items.cell"你的列".text.ToString("yyyy-MM-dd")9獲取錯誤信息并到指定頁面不要使用Response.Redirect,而應該使用Server.Transfere.g/ in global.asaxprotected void Application_Error(Object sender, EventArgs e) if (Server.GetLastError()

14、 is HttpUnhandledException)Server.Transfer("MyErrorPage.aspx");/其余的非HttpUnhandledException異常交給ASP.NET自己處理就okay了 :)Redirect會導致postback的產生從而丟失了錯誤信息,所以頁面導向應該直接在服務器端執(zhí)行,這樣就可以在錯誤處理頁面得到出錯信息并進行相應的處理 10清空CookieCookie.Expires=DateTime;Response.Cookies("UserName").Expires = 011自定義異常處理/自定義異常

15、處理類 using System;using System.Diagnostics;namespace MyAppException/ summary/ 從系統(tǒng)異常類ApplicationException繼承的應用程序異常處理類。/ 自動將異常內容記錄到Windows NT/2000的應用程序日志/ /summarypublic class AppException:System.ApplicationExceptionpublic AppException()if (ApplicationConfiguration.EventLogEnabled)LogEvent("出現一個未知

16、錯誤。");public AppException(string message)LogEvent(message);public AppException(string message,Exception innerException)LogEvent(message);if (innerException != null)LogEvent(innerException.Message);/日志記錄類using System;using System.Configuration;using System.Diagnostics;using System.IO;using Syste

17、m.Text;using System.Threading;namespace MyEventLog/ summary/ 事件日志記錄類,提供事件日志記錄支持 / remarks/ 定義了4個日志記錄方法 (error, warning, info, trace) / /remarks/ /summarypublic class ApplicationLog/ summary/ 將錯誤信息記錄到Win2000/NT事件日志中/ param name="message"需要記錄的文本信息/param/ /summarypublic static void WriteError

18、(String message)WriteLog(TraceLevel.Error, message);/ summary/ 將警告信息記錄到Win2000/NT事件日志中/ param name="message"需要記錄的文本信息/param/ /summarypublic static void WriteWarning(String message)WriteLog(TraceLevel.Warning, message);/ summary/ 將提示信息記錄到Win2000/NT事件日志中/ param name="message"需要記錄的文

19、本信息/param/ /summarypublic static void WriteInfo(String message)WriteLog(TraceLevel.Info, message);/ summary/ 將跟蹤信息記錄到Win2000/NT事件日志中/ param name="message"需要記錄的文本信息/param/ /summarypublic static void WriteTrace(String message)WriteLog(TraceLevel.Verbose, message);/ summary/ 格式化記錄到事件日志的文本信息格式

20、/ param name="ex"需要格式化的異常對象/param/ param name="catchInfo"異常信息標題字符串./param/ retvalue/ para格式后的異常信息字符串,包括異常內容和跟蹤堆棧./para/ /retvalue/ /summarypublic static String FormatException(Exception ex, String catchInfo)StringBuilder strBuilder = new StringBuilder();if (catchInfo != String.Em

21、pty)strBuilder.Append(catchInfo).Append("rn"); /相似于Java中的StringBufferstrBuilder.Append(ex.Message).Append("rn").Append(ex.StackTrace);return strBuilder.ToString();/ summary/ 實際事件日志寫入方法/ param name="level"要記錄信息的級別(error,warning,info,trace)./param/ param name="messag

22、eText"要記錄的文本./param/ /summaryprivate static void WriteLog(TraceLevel level, String messageText)try EventLogEntryType LogEntryType;switch (level)case TraceLevel.Error:LogEntryType = EventLogEntryType.Error;break;case TraceLevel.Warning:LogEntryType = EventLogEntryType.Warning;break;case TraceLev

23、el.Info:LogEntryType = EventLogEntryType.Information;break;case TraceLevel.Verbose:LogEntryType = EventLogEntryType.SuccessAudit;break;default:LogEntryType = EventLogEntryType.SuccessAudit;break;EventLog eventLog = new EventLog("Application", ApplicationConfiguration.EventLogMachineName, A

24、pplicationConfiguration.EventLogSourceName );/寫入事件日志eventLog.WriteEntry(messageText, LogEntryType);catch /忽略任何異常 /class ApplicationLog12Panel 橫向滾動,縱向自動擴展asp:panel style="overflow-x:scroll;overflow-y:auto;"/asp:panel13回車轉換成Tab event.keyCode = 13 是回車;event.keyCode = 9 是換行。script language=&qu

25、ot;javascript" for="document" event="onkeydown"if(event.keyCode=13 && event.srcElement.type != button && event.srcElement.type != submit && event.srcElement.type!=reset &&event.srcElement.type != && event.srcElement.type != textarea) e

26、vent.keyCode=9;/scriptonkeydown="if(event.keyCode=13) event.keyCode = 9"14DataGrid超級連接列DataNavigateUrlField="字段名" DataNavigateUrlFormatString="http:/xx/inc/delete.aspx?ID=0" /這里應該是通配符15DataGrid行隨鼠標變色private void DGzf_ItemDataBound(object sender, System.Web.UI.WebControl

27、s.DataGridItemEventArgs e)if (e.Item.ItemType != ListItemType.Header)e.Item.Attributes.Add( "onmouseout","this.style.backgroundColor=""+e.Item.Style"BACKGROUND-COLOR"+"""); /鼠標移出 e.Item.Attributes.Add( "onmouseover","this.style.backgro

28、undColor=""+ "#EFF3F7"+"""); /鼠標移入16模板列ASP:TEMPLATECOLUMN visible="False" sortexpression="demo" headertext="ID"ITEMTEMPLATEASP:LABEL text=%# DataBinder.Eval(Container.DataItem, "ArticleID")% runat="server" width=&qu

29、ot;80%" id="lblColumn" /ITEMTEMPLATE/ASP:TEMPLATECOLUMNASP:TEMPLATECOLUMN headertext="選中"HEADERSTYLE wrap="False" horizontalalign="Center"/HEADERSTYLEITEMTEMPLATEASP:CHECKBOX id="chkExport" runat="server" /ITEMTEMPLATEEDITITEMTEMPLATEA

30、SP:CHECKBOX id="chkExportON" runat="server" enabled="true" /EDITITEMTEMPLATE/ASP:TEMPLATECOLUMN后臺代碼protected void CheckAll_CheckedChanged(object sender, System.EventArgs e)/改變列的選定,實現全選或全不選。CheckBox chkExport ;if( CheckAll.Checked)foreach(DataGridItem oDataGridItem in My

31、DataGrid.Items)chkExport = (CheckBox)oDataGridItem.FindControl("chkExport");chkExport.Checked = true;elseforeach(DataGridItem oDataGridItem in MyDataGrid.Items)chkExport = (CheckBox)oDataGridItem.FindControl("chkExport");chkExport.Checked = false;17數字格式化【%#Container.DataItem(&quo

32、t;price")%的結果是500.0000,怎樣格式化為500.00?】%#Container.DataItem("price","0:¥#,#0.00")%int i=123456;string s=i.ToString("#,#.00");18日期格式化【aspx頁面內:%# DataBinder.Eval(Container.DataItem,"Company_Ureg_Date")%顯示為: 2004-8-11 19:44:28我只想要:2004-8-11 】%# DataBinder.Eval

33、(Container.DataItem,"Company_Ureg_Date","0:yyyy-M-d")%應該如何改?【格式化日期】取出來,一般是object(DateTime)objectFromDB).ToString("yyyy-MM-dd");【日期的驗證表達式】A.以下正確的輸入格式: 2004-2-29, 2004-02-29 10:29:39 pm, 2004/12/31 (d2(02468048)|(1357926)-/s?(0?13578)|(102)-/s?(0?1-9)|(1-20-9)|(301)|(0?46

34、9)|(11)-/s?(0?1-9)|(1-20-9)|(30)|(0?2-/s?(0?1-9)|(1-20-9)|(d2(024681235679)|(1357901345789)-/s?(0?13578)|(102)-/s?(0?1-9)|(1-20-9)|(301)|(0?469)|(11)-/s?(0?1-9)|(1-20-9)|(30)|(0?2-/s?(0?1-9)|(10-9)|(20-8)(s(0?1-9)|(10-2):(0-50-9)(s)|(:(0-50-9)s)(AM|PM|am|pm2,2)?$B.以下正確的輸入格式:0001-12-31, 9999 09 30, 2

35、002/03/03 d4-/s?(013578)|(102)-/s?(0-20-9)|(301)|(0469)|(11)-/s?(0-20-9)|(30)|(02-/s?0-20-9)$ 【大小寫轉換】HttpUtility.HtmlEncode(string);HttpUtility.HtmlDecode(string);19如何設定全局變量Global.asax中Application_Start()事件中添加Application屬性名 xxx;就是你的全局變量20怎樣做到HyperLinkColumn生成的連接后,點擊連接,打開新窗口?HyperLinkColumn有個屬性Target

36、,將其值設置成"_blank"即可.(Target="_blank")【ASPNETMENU】點擊菜單項彈出新窗口在你的menuData.xml文件的菜單項中加入URLTarget="_blank",如:?xml version="1.0" encoding="GB2312"?MenuData ImagesBaseURL="images/" MenuGroupMenuItem Label="內參信息" URL="Infomation.aspx&q

37、uot; MenuGroup ID="BBC"MenuItem Label="公告信息" URL="Infomation.aspx" URLTarget="_blank" LeftIcon="file.gif"/MenuItem Label="編制信息簡報" URL="NewInfo.aspx" LeftIcon="file.gif" /.最好將你的aspnetmenu升級到1.2版21讀取DataGrid控件TextBox值forea

38、ch(DataGrid dgi in yourDataGrid.Items)TextBox tb = (TextBox)dgi.FindControl("yourTextBoxId");tb.Text.23自動模板列計算:在錄入數量及單價的時候自動算出金額在DataGrid中有3個模板列包含Textbox分別為 DG_ShuLiang (數量) DG_DanJian(單價) DG_JinE(金額)分別在5.6.7列,要求在錄入數量及單價的時候自動算出金額即:數量*單價=金額還要求錄入時限制為 數值型.我如何用客戶端腳本實現這個功能?思歸asp:TemplateColumn

39、HeaderText="數量" ItemTemplateasp:TextBox id="ShuLiang" runat=server Text=%# DataBinder.Eval(Container.DataItem,"DG_ShuLiang")% onkeyup="javascript:DoCal()"/asp:RegularExpressionValidator id="revS" runat="server" ControlToValidate="ShuLi

40、ang" ErrorMessage="must be integer" ValidationExpression="d+$" /ItemTemplate/asp:TemplateColumnasp:TemplateColumn HeaderText="單價" ItemTemplateasp:TextBox id="DanJian" runat=server Text=%# DataBinder.Eval(Container.DataItem,"DG_DanJian")% onkeyup

41、="javascript:DoCal()"/asp:RegularExpressionValidator id="revS2" runat="server" ControlToValidate="DanJian" ErrorMessage="must be numeric" ValidationExpression="d+(.d*)?$" /ItemTemplate/asp:TemplateColumnasp:TemplateColumn HeaderText="金

42、額" ItemTemplateasp:TextBox id="JinE" runat=server Text=%# DataBinder.Eval(Container.DataItem,"DG_JinE")% /ItemTemplate/asp:TemplateColumnscript language="javascript"function DoCal()var e = event.srcElement;var row = e.parentNode.parentNode;var txts = row.all.tags(&

43、quot;INPUT");if (!txts.length | txts.length 3)return;var q = txtstxts.length-3.value;var p = txtstxts.length-2.value;if (isNaN(q) | isNaN(p)return;q = parseInt(q);p = parseFloat(p);txtstxts.length-1.value = (q * p).toFixed(2);/script24datagrid選定比較底下的行時,為什么總是刷新一下,然后就滾動到了最上面,剛才選定的行因屏幕的關系就看不到了。pag

44、e_load page.smartNavigation=true25在Datagrid中修改數據,當點擊編輯鍵時,數據出現在文本框中,怎么控制文本框的大小 ? private void DataGrid1_ItemDataBound(obj sender,DataGridItemEventArgs e)for(int i=0;ie.Item.Cells.Count-1;i+)if(e.Item.ItemType=ListItemType.EditType)e.Item.Cellsi.Attributes.Add("Width", "80px") 26對話

45、框private static string ScriptBegin = "script language="JavaScript""private static string ScriptEnd = "/script"public static void ConfirmMessageBox(string PageTarget,string Content)string ConfirmContent="var retValue=window.confirm("+Content+");"+&quo

46、t;if(retValue)window.location="+PageTarget+""ConfirmContent=ScriptBegin + ConfirmContent + ScriptEnd;Page ParameterPage = (Page)System.Web.HttpContext.Current.Handler;ParameterPage.RegisterStartupScript("confirm",ConfirmContent);/Response.Write(strScript);27將時間格式化:string aa=

47、DateTime.Now.ToString("yyyy年MM月dd日"); 1.1 取當前年月日時分秒 currentTime=System.DateTime.Now;1.2 取當前年 int 年= DateTime.Now.Year;1.3 取當前月 int 月= DateTime.Now.Month; 1.4 取當前日 int 日= DateTime.Now.Day; 1.5 取當前時 int 時= DateTime.Now.Hour; 1.6 取當前分 int 分= DateTime.Now.Minute; 1.7 取當前秒 int 秒= DateTime.Now.S

48、econd; 1.8 取當前毫秒 int 毫秒= DateTime.Now.Millisecond; 28自定義分頁代碼:先定義變量 :public static int pageCount; /總頁面數 public static int curPageIndex=1; /當前頁面 下一頁: if(DataGrid1.CurrentPageIndex (DataGrid1.PageCount - 1) DataGrid1.CurrentPageIndex += 1; curPageIndex+=1; bind(); / DataGrid1數據綁定函數 上一頁: if(DataGrid1.Cu

49、rrentPageIndex 0) DataGrid1.CurrentPageIndex += 1; curPageIndex-=1; bind(); / DataGrid1數據綁定函數 直接頁面跳轉: int a=int.Parse(JumpPage.Value.Trim();/JumpPage.Value.Trim()為跳轉值 if(aDataGrid1.PageCount) this.DataGrid1.CurrentPageIndex=a; bind(); 29DataGrid使用: 添加刪除確認: private void DataGrid1_ItemCreated(object s

50、ender, System.Web.UI.WebControls.DataGridItemEventArgs e) foreach(DataGridItem di in this.DataGrid1.Items) if(di.ItemType=ListItemType.Item|di.ItemType=ListItemType.AlternatingItem) (LinkButton)di.Cells8.Controls0).Attributes.Add("onclick","return confirm(確認刪除此項嗎?);"); 樣式交替: List

51、ItemType itemType = e.Item.ItemType; if (itemType = ListItemType.Item ) e.Item.Attributes"onmouseout" = "javascript:this.style.backgroundColor=#FFFFFF;" e.Item.Attributes"onmouseover" = "javascript:this.style.backgroundColor=#d9ece1;cursor=hand;" ; else if( it

52、emType = ListItemType.AlternatingItem) e.Item.Attributes"onmouseout" = "javascript:this.style.backgroundColor=#a0d7c4;" e.Item.Attributes"onmouseover" = "javascript:this.style.backgroundColor=#d9ece1;cursor=hand;" ; 添加一個編號列: DataTable dt= c.ExecuteRtnTableForA

53、ccess(sqltxt); /執(zhí)行sql返回的DataTable DataColumn dc=dt.Columns.Add("number",System.Type.GetType("System.String"); for(int i=0;idt.Rows.Count;i+) dt.Rowsi"number"=(i+1).ToString(); DataGrid1.DataSource=dt; DataGrid1.DataBind(); DataGrid1中添加一個CheckBox,頁面中添加一個全選框 private void

54、CheckBox2_CheckedChanged(object sender, System.EventArgs e) foreach(DataGridItem thisitem in DataGrid1.Items) (CheckBox)thisitem.Cells0.Controls1).Checked=CheckBox2.Checked; 將當前頁面中DataGrid1顯示的數據全部刪除 foreach(DataGridItem thisitem in DataGrid1.Items) if(CheckBox)thisitem.Cells0.Controls1).Checked) str

55、ing strloginid= DataGrid1.DataKeysthisitem.ItemIndex.ToString(); Del (strloginid); /刪除函數 30當文件在不同目錄下,需要獲取數據庫連接字符串(如果連接字符串放在Web.config,然后在Global.asax中初始化) 在Application_Start中添加以下代碼: Application"ConnStr"=this.Context.Request.PhysicalApplicationPath+ConfigurationSettings.AppSettings"ConnStr".ToString();31變量.ToString() 字符型轉換 轉

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論