ASP.NET程序中常用的三十三种代码(一)

1. 打开新的窗口并传送参数
1 response.write("<script> window .open('* .asp x?id="+this.DropDownList1.SelectIndex+"&id1="++"')</script>")
接收参数:
1 string a = Request.QueryString("id");
2 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.删除表格选定记录
1 int intEmpID = (int)MyDataGrid.DataKeys[e.Item.ItemIndex];
2 string deleteCmd = "DELETE from Employee where emp_id = " + intEmpID.ToString()
4.删除表格记录警告
 1 private void DataGrid _ItemCreated( Object sender,DataGridItemEventArgs e)
 2 {
 3   switch(e.Item.ItemType)
 4   {
 5    case ListItemType.Item :
 6    case ListItemType.AlternatingItem :
 7    case ListItemType.EditItem:
 8     TableCell myTableCell;
 9     myTableCell = e.Item.Cells[14];
10     LinkButton myDeleteButton ;
11     myDeleteButton = (LinkButton)myTableCell.Controls[0];
12     myDeleteButton.Attributes.Add("onclick","return confirm('您是否确定要删除这条信息');");
13     break;
14    default:
15     break;
16   }
17 }
18 
5.点击表格行链接另一页
 1 private void grdCustomer_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
 2 {
 3   //点击表格打开
 4   if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
 5    e.Item.Attributes.Add("onclick","window.open('Default.aspx?id=" + e.Item.Cells[0]. Text + "');");
 6 }
 7 
 8    双击表格连接到另一页
 9 
10    在itemDataBind事件中
11 if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
12 {
13   string OrderItemID =e.item.cells[1].Text;
14   
15   e.item.Attributes.Add("ondblclick""location.href='../ShippedGrid.aspx?id=" + OrderItemID + "'");
16 }
17 
双击表格打开新一页
1 if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
2 {
3   string OrderItemID =e.item.cells[1].Text;
4   
5   e.item.Attributes.Add("ondblclick""open('../ShippedGrid.aspx?id=" + OrderItemID + "')");
6 }
7 
★特别注意:【?id=】 处不能为 【?id =】
6.表格超连接列传递参数
1 <asp:HyperLinkColumn Target="_blank" headertext="ID号" DataTextField="id" NavigateUrl="aaa.aspx?id='
2   <%# DataBinder.Eval(Container.DataItem, "数据字段1")%' & name='%# DataBinder.Eval(Container.DataItem, "数据字段2")%' />
7.表格点击改变颜色
1 if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem)
2 {
3   e.Item.Attributes.Add("onclick","this.style.backgroundColor='#99cc00';
4     this.style.color='buttontext';this.style.cursor='default';");
5 }
6 
写在DataGrid的_ItemDataBound里
1 if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem)
2 {
3 e.Item.Attributes.Add("onmouseover","this.style.backgroundColor='#99cc00';
4     this.style.color='buttontext';this.style.cursor='default';");
5 e.Item.Attributes.Add("onmouseout","this.style.backgroundColor='';this.style.color='';");
6 }
7 
8.关于日期格式
1 DataFormatString="{0:yyyy-MM-dd}"  
2 
1 e.items.cell["你的列"].text=DateTime.Parse(e.items.cell["你的列"].text.ToString("yyyy-MM-dd"))  
9.获取错误信息并到指定页面
1 protected void Application_Error(Object sender, EventArgs e) 
2 {
3 if (Server.GetLastError() is HttpUnhandledException)
4 Server.Transfer("MyErrorPage.aspx");
5 }
6 
Redirect会导致post-back的产生从而丢失了错误信息,所以页面导向应该直接在服务器端执行,这样就可以在错误处理页面得到出错信息并进行相应的处理
10.清空Cookie
1 Cookie.Expires=[DateTime];
2 Response.Cookies("UserName").Expires = 0
11.自定义异常处理
  1 //自定义异常处理类
  2 using System;
  3 using System.Diagnostics;
  4 
  5 namespace MyAppException
  6 {
  7   /// <summary>
  8   /// 从系统异常类ApplicationException继承的应用程序异常处理类。
  9   /// 自动将异常内容记录到Windows NT/2000的应用程序日志
 10   /// </summary>
 11   public class AppException:System.ApplicationException
 12   {
 13    public AppException()
 14    {
 15     if (ApplicationConfiguration.EventLogEnabled)LogEvent("出现一个未知错误。");
 16    }
 17 
 18   public AppException(string message)
 19   {
 20    LogEvent(message);
 21   }
 22 
 23   public AppException(string message,Exception innerException)
 24   {
 25    LogEvent(message);
 26    if (innerException != null)
 27    {
 28     LogEvent(innerException.Message);
 29    }
 30   }
 31 
 32   //日志记录类
 33   using System;
 34   using System.Configuration;
 35   using System.Diagnostics;
 36   using System.IO;
 37   using System.Text;
 38   using System.Threading;
 39 
 40   namespace MyEventLog
 41   {
 42    /// <summary>
 43    /// 事件日志记录类,提供事件日志记录支持
 44    /// <remarks>
 45    /// 定义了4个日志记录方法 (error, warning, info, trace)
 46    /// </remarks>
 47    /// </summary>
 48    public class ApplicationLog
 49    {
 50     /// <summary>
 51     /// 将错误信息记录到Win2000/NT事件日志中
 52     /// <param name="message">需要记录的文本信息</param>
 53     /// </summary>
 54     public static void WriteError(String message)
 55     {
 56      WriteLog(TraceLevel.Error, message);
 57     }
 58 
 59     /// <summary>
 60     /// 将警告信息记录到Win2000/NT事件日志中
 61     /// <param name="message">需要记录的文本信息</param>
 62     /// </summary>
 63     public static void WriteWarning(String message)
 64     {
 65      WriteLog(TraceLevel.Warning, message);  
 66     }
 67 
 68     /// <summary>
 69     /// 将提示信息记录到Win2000/NT事件日志中
 70     /// <param name="message">需要记录的文本信息</param>
 71     /// </summary>
 72     public static void WriteInfo(String message)
 73     {
 74      WriteLog(TraceLevel.Info, message);
 75     }
 76     /// <summary>
 77     /// 将跟踪信息记录到Win2000/NT事件日志中
 78     /// <param name="message">需要记录的文本信息</param>
 79     /// </summary>
 80     public static void WriteTrace(String message)
 81     {
 82      WriteLog(TraceLevel.Verbose, message);
 83     }
 84 
 85     /// <summary>
 86     /// 格式化记录到事件日志的文本信息格式
 87     /// <param name="ex">需要格式化的异常对象</param>
 88     /// <param name="catchInfo">异常信息标题字符串.</param>
 89     /// <retvalue>
 90     /// <para>格式后的异常信息字符串,包括异常内容和跟踪堆栈.</para>
 91     /// </retvalue>
 92     /// </summary>
 93     public static String FormatException(Exception ex, String catchInfo)
 94     {
 95      StringBuilder strBuilder = new StringBuilder();
 96      if (catchInfo != String.Empty)
 97      {
 98       strBuilder.Append(catchInfo).Append("\r\n");
 99      }
100      strBuilder.Append(ex.Message).Append("\r\n").Append(ex.StackTrace);
101      return strBuilder.ToString();
102     }
103 
104     /// <summary>
105     /// 实际事件日志写入方法
106     /// <param name="level">要记录信息的级别(error,warning,info,trace).</param>
107     /// <param name="messageText">要记录的文本.</param>
108     /// </summary>
109     private static void WriteLog(TraceLevel level, String messageText)
110     {
111      try
112      {
113       EventLogEntryType LogEntryType;
114       switch (level)
115       {
116        case TraceLevel.Error:
117         LogEntryType = EventLogEntryType.Error;
118         break;
119        case TraceLevel.Warning:
120         LogEntryType = EventLogEntryType.Warning;
121         break;
122        case TraceLevel.Info:
123         LogEntryType = EventLogEntryType.Information;
124         break;
125        case TraceLevel.Verbose:
126         LogEntryType = EventLogEntryType.SuccessAudit;
127         break;
128        default:
129         LogEntryType = EventLogEntryType.SuccessAudit;
130         break;
131       }
132 
133       EventLog eventLog = new EventLog("Application", ApplicationConfiguration.EventLogMachineName, ApplicationConfiguration.EventLogSourceName );
134       //写入事件日志
135       eventLog.WriteEntry(messageText, LogEntryType);
136 
137      }
138     catch {} //忽略任何异常
139    }
140   } //class ApplicationLog
141 }
142 
12.Panel 横向滚动,纵向自动扩展
1 <asp:panel style="overflow-x:scroll;overflow-y:auto;"></asp:panel>
13.回车转换成Tab 
1 <script language="javascript" for="document" event="onkeydown"
2   if(event.keyCode==13 && event.srcElement.type!='button' && event.srcElement.type!='submit' &&     event.srcElement.type!='reset' && event.srcElement.type!=''&& event.srcElement.type!='textarea');
3     event.keyCode=9;
4 /script>
5 
6 onkeydown="if(event.keyCode==13) event.keyCode=9"
7 
14.DataGrid超级连接列
1 DataNavigateUrlField="字段名" DataNavigateUrlFormatString="http://xx/inc/delete.aspx?ID={0}"
15.DataGrid行随鼠标变色
1 private void DGzf_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
2 {
3   if (e.Item.ItemType!=ListItemType.Header)
4   {
5    e.Item.Attributes.Add( "onmouseout","this.style.backgroundColor=\""+e.Item.Style["BACKGROUND-COLOR"]+"\"");
6    e.Item.Attributes.Add( "onmouseover","this.style.backgroundColor=\"""#EFF3F7"+"\"");
7   }
8 }
9 
16.模板列
 1 <ASP:TEMPLATECOLUMN visible="False" sortexpression="demo" headertext="ID"
 2 <ITEMTEMPLATE>
 3 <ASP:LABEL text='<%# DataBinder.Eval(Container.DataItem, "ArticleID")%>' runat="server" width="80%" id="lblColumn" /
 4 /ITEMTEMPLATE>
 5 /ASP:TEMPLATECOLUMN>
 6 
 7 <ASP:TEMPLATECOLUMN headertext="选中"
 8 <HEADERSTYLE wrap="False" horizontalalign="Center"></HEADERSTYLE>
 9 <ITEMTEMPLATE>
10 <ASP:CHECKBOX id="chkExport" runat="server" /
11 /ITEMTEMPLATE>
12 <EDITITEMTEMPLATE>
13 <ASP:CHECKBOX id="chkExportON" runat="server" enabled="true" /
14 /EDITITEMTEMPLATE>
15 /ASP:TEMPLATECOLUMN>  
16 
17    后台代码
18 
19 protected void CheckAll_CheckedChanged(object sender, System.EventArgs e)
20 {
21   //改变列的选定,实现全选或全不选。
22   CheckBox chkExport ;
23   if( CheckAll.Checked)
24   {
25    foreach(DataGridItem oDataGridItem in MyDataGrid.Items)
26    {
27     chkExport = (CheckBox)oDataGridItem.FindControl("chkExport");
28     chkExport.Checked = true;
29    }
30   }
31   else
32   {
33    foreach(DataGridItem oDataGridItem in MyDataGrid.Items)
34    {
35     chkExport = (CheckBox)oDataGridItem.FindControl("chkExport");
36     chkExport.Checked = false;
37    }
38   }
39 }
原文地址:https://www.cnblogs.com/cxy521/p/1048404.html