搜尋
首頁後端開發C#.Net教程ASP.NET中常用的種程式碼實例解析

ASP.NET中常用的種程式碼實例解析

Apr 26, 2017 am 10:53 AM
asp.net

1. 開啟新的視窗並傳送參數: 
傳送參數:

response.write("<script>window.open('*.aspx?id="+this.DropDownList1.SelectIndex+"&id1="+...+"')</script>")

接收參數:

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;}else{return false;}")

3.刪除表格選定記錄

int intEmpID = (int)MyDataGrid.DataKeys[e.Item.ItemIndex]; 
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 : 
  case ListItemType.AlternatingItem : 
  case ListItemType.EditItem: 
   TableCell myTableCell; 
   myTableCell = e.Item.Cells[14]; 
   LinkButton myDeleteButton ; 
   myDeleteButton = (LinkButton)myTableCell.Controls[0]; 
   myDeleteButton.Attributes.Add("onclick","return confirm('您是否确定要删除这条信息');"); 
   break; 
  default: 
   break; 
 } 
}

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.Item.Cells[0].Text + "');"); 
} 
双击表格连接到另一页 
在itemDataBind事件中 
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
{ 
 string OrderItemID =e.item.cells[1].Text; 
 ... 
 e.item.Attributes.Add("ondblclick", "location.href='../ShippedGrid.aspx?id=" + OrderItemID + "'"); 
} 
   
双击表格打开新一页 
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
{ 
 string OrderItemID =e.item.cells[1].Text; 
 ... 
 e.item.Attributes.Add("ondblclick", "open('../ShippedGrid.aspx?id=" + OrderItemID + "')"); 
}

6.表格超連接列傳遞參數

<asp:HyperLinkColumn 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.ItemType == 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) 
{ 
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-dd}" 
  我觉得应该在itembound事件中 
e.items.cell["你的列"].text=DateTime.Parse(e.items.cell["你的列"].text.ToString("yyyy-MM-dd"))

  9.取得錯誤訊息並到指定頁面
  不要使用Response.Redirect,而應該使用Server.Transfer
  e.g

// in global.asax 
protected void Application_Error(Object sender, EventArgs e) { 
if (Server.GetLastError() is HttpUnhandledException) 
Server.Transfer("MyErrorPage.aspx"); 
//其余的非HttpUnhandledException异常交给ASP.NET自己处理就okay了 :) 
} 
  Redirect会导致post-back的产生从而丢失了错误信息,所以页面导向应该直接在服务器端执行,这样就可以在错误处理页面得到出错信息并进行相应的处理
##10.清空Cookie


Cookie.Expires=[DateTime]; 
Response.Cookies("UserName").Expires = 0

11.自訂異常處理


//自定义异常处理类  
using System; 
using System.Diagnostics; 
namespace MyAppException 
{ 
 /// <summary> 
 /// 从系统异常类ApplicationException继承的应用程序异常处理类。 
 /// 自动将异常内容记录到Windows NT/2000的应用程序日志 
 /// </summary> 
 public class AppException:System.ApplicationException 
 { 
  public AppException() 
  { 
   if (ApplicationConfiguration.EventLogEnabled)LogEvent("出现一个未知错误。"); 
  } 
 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 System.Text; 
 using System.Threading; 
 namespace MyEventLog 
 { 
  /// <summary> 
  /// 事件日志记录类,提供事件日志记录支持  
  /// <remarks> 
  /// 定义了4个日志记录方法 (error, warning, info, trace)  
  /// </remarks> 
  /// </summary> 
  public class ApplicationLog 
  { 
   /// <summary> 
   /// 将错误信息记录到Win2000/NT事件日志中 
   /// <param name="message">需要记录的文本信息</param> 
   /// </summary> 
   public static void WriteError(String message) 
   { 
    WriteLog(TraceLevel.Error, message); 
   } 
   /// <summary> 
   /// 将警告信息记录到Win2000/NT事件日志中 
   /// <param name="message">需要记录的文本信息</param> 
   /// </summary> 
   public static void WriteWarning(String message) 
   { 
    WriteLog(TraceLevel.Warning, message);   
   } 
   /// <summary> 
   /// 将提示信息记录到Win2000/NT事件日志中 
   /// <param name="message">需要记录的文本信息</param> 
   /// </summary> 
   public static void WriteInfo(String message) 
   { 
    WriteLog(TraceLevel.Info, message); 
   } 
   /// <summary> 
   /// 将跟踪信息记录到Win2000/NT事件日志中 
   /// <param name="message">需要记录的文本信息</param> 
   /// </summary> 
   public static void WriteTrace(String message) 
   { 
    WriteLog(TraceLevel.Verbose, message); 
   } 
   /// <summary> 
   /// 格式化记录到事件日志的文本信息格式 
   /// <param name="ex">需要格式化的异常对象</param> 
   /// <param name="catchInfo">异常信息标题字符串.</param> 
   /// <retvalue> 
   /// <para>格式后的异常信息字符串,包括异常内容和跟踪堆栈.</para> 
   /// </retvalue> 
   /// </summary> 
   public static String FormatException(Exception ex, String catchInfo) 
   { 
    StringBuilder strBuilder = new StringBuilder(); 
    if (catchInfo != String.Empty) 
    { 
     strBuilder.Append(catchInfo).Append("\r\n"); 
    } 
    strBuilder.Append(ex.Message).Append("\r\n").Append(ex.StackTrace); 
    return strBuilder.ToString(); 
   } 
   /// <summary> 
   /// 实际事件日志写入方法 
   /// <param name="level">要记录信息的级别(error,warning,info,trace).</param> 
   /// <param name="messageText">要记录的文本.</param> 
   /// </summary> 
   private 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 TraceLevel.Info: 
       LogEntryType = EventLogEntryType.Information; 
       break; 
      case TraceLevel.Verbose: 
       LogEntryType = EventLogEntryType.SuccessAudit; 
       break; 
      default: 
       LogEntryType = EventLogEntryType.SuccessAudit; 
       break; 
     } 
     EventLog eventLog = new EventLog("Application", ApplicationConfiguration.EventLogMachineName, ApplicationConfiguration.EventLogSourceName ); 
     //写入事件日志 
     eventLog.WriteEntry(messageText, LogEntryType); 
    } 
   catch {} //忽略任何异常 
  }  
 } //class ApplicationLog 
}

以上是ASP.NET中常用的種程式碼實例解析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
C#.NET用於網絡,桌面和移動開發C#.NET用於網絡,桌面和移動開發Apr 25, 2025 am 12:01 AM

C#和.NET適用於Web、桌面和移動開發。 1)在Web開發中,ASP.NETCore支持跨平台開發。 2)桌面開發使用WPF和WinForms,適用於不同需求。 3)移動開發通過Xamarin實現跨平台應用。

C#.NET生態系統:框架,庫和工具C#.NET生態系統:框架,庫和工具Apr 24, 2025 am 12:02 AM

C#.NET生態系統提供了豐富的框架和庫,幫助開發者高效構建應用。 1.ASP.NETCore用於構建高性能Web應用,2.EntityFrameworkCore用於數據庫操作。通過理解這些工具的使用和最佳實踐,開發者可以提高應用的質量和性能。

將C#.NET應用程序部署到Azure/AWS:逐步指南將C#.NET應用程序部署到Azure/AWS:逐步指南Apr 23, 2025 am 12:06 AM

如何將C#.NET應用部署到Azure或AWS?答案是使用AzureAppService和AWSElasticBeanstalk。 1.在Azure上,使用AzureAppService和AzurePipelines自動化部署。 2.在AWS上,使用AmazonElasticBeanstalk和AWSLambda實現部署和無服務器計算。

C#.NET:強大的編程語言簡介C#.NET:強大的編程語言簡介Apr 22, 2025 am 12:04 AM

C#和.NET的結合為開發者提供了強大的編程環境。 1)C#支持多態性和異步編程,2).NET提供跨平台能力和並發處理機制,這使得它們在桌面、Web和移動應用開發中廣泛應用。

.NET框架與C#:解碼術語.NET框架與C#:解碼術語Apr 21, 2025 am 12:05 AM

.NETFramework是一個軟件框架,C#是一種編程語言。 1..NETFramework提供庫和服務,支持桌面、Web和移動應用開發。 2.C#設計用於.NETFramework,支持現代編程功能。 3..NETFramework通過CLR管理代碼執行,C#代碼編譯成IL後由CLR運行。 4.使用.NETFramework可快速開發應用,C#提供如LINQ的高級功能。 5.常見錯誤包括類型轉換和異步編程死鎖,調試需用VisualStudio工具。

揭開c#.net的神秘面紗:初學者的概述揭開c#.net的神秘面紗:初學者的概述Apr 20, 2025 am 12:11 AM

C#是一種由微軟開發的現代、面向對象的編程語言,.NET是微軟提供的開發框架。 C#結合了C 的性能和Java的簡潔性,適用於構建各種應用程序。 .NET框架支持多種語言,提供垃圾回收機制,簡化內存管理。

C#和.NET運行時:它們如何一起工作C#和.NET運行時:它們如何一起工作Apr 19, 2025 am 12:04 AM

C#和.NET運行時緊密合作,賦予開發者高效、強大且跨平台的開發能力。 1)C#是一種類型安全且面向對象的編程語言,旨在與.NET框架無縫集成。 2).NET運行時管理C#代碼的執行,提供垃圾回收、類型安全等服務,確保高效和跨平台運行。

C#.NET開發:入門的初學者指南C#.NET開發:入門的初學者指南Apr 18, 2025 am 12:17 AM

要開始C#.NET開發,你需要:1.了解C#的基礎知識和.NET框架的核心概念;2.掌握變量、數據類型、控制結構、函數和類的基本概念;3.學習C#的高級特性,如LINQ和異步編程;4.熟悉常見錯誤的調試技巧和性能優化方法。通過這些步驟,你可以逐步深入C#.NET的世界,並編寫高效的應用程序。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。