代码改变世界

ASP.NET Web开发实用代码(二)

2008-12-25 14:43  TTlive  阅读(145)  评论(0编辑  收藏  举报

1.表格超连接列传递参数

  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")%>' /> 

2.表格点击改变颜色

  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. }

写在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. }

3.关于日期格式

日期格式设定

  1. DataFormatString="{0:yyyy-MM-dd}"

我觉得应该在itembound事件中

  1. e.items.cell["你的列"].text=DateTime.Parse(e.items.cell["你的列"].text.ToString("yyyy-MM-dd"))

4.获取错误信息并到指定页面

不要使用Response.Redirect,而应该使用Server.Transfer

  1. // in global.asax
  2. protected void Application_Error(Object sender, EventArgs e) {
  3.     if (Server.GetLastError() is HttpUnhandledException)
  4.     Server.Transfer("MyErrorPage.aspx");//其余的非HttpUnhandledException异常交给ASP.NET自己处理就okay了:)

其余的非HttpUnhandledException异常交给ASP.NET自己处理就okay了。

Redirect会导致post-back的产生从而丢失了错误信息,所以页面导向应该直接在服务器端执行,这样就可以在错误处理页面得到出错信息并进行相应的处理。

5.清空Cookie

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

6.自定义异常处理

  1. //自定义异常处理类 
  2. using System;
  3. using System.Diagnostics;
  4. namespace MyAppException
  5. {
  6.     /// <summary>
  7.     /// 从系统异常类ApplicationException继承的应用程序异常处理类。
  8.     /// 自动将异常内容记录到Windows NT/2000的应用程序日志
  9.     /// </summary>
  10.     public class AppException:System.ApplicationException
  11.     {
  12.         public AppException(){
  13.             if (ApplicationConfiguration.EventLogEnabled)LogEvent("出现一个未知错误。");
  14.         }
  15.         public AppException(string message){
  16.             LogEvent(message);
  17.         }
  18.         public AppException(string message,Exception innerException)
  19.         {
  20.             LogEvent(message);
  21.             if (innerException != null){
  22.                 LogEvent(innerException.Message);
  23.             }
  24.         }
  25.     }
  26. }
  27. //日志记录类
  28. using System;
  29. using System.Configuration;
  30. using System.Diagnostics;
  31. using System.IO;
  32. using System.Text;
  33. using System.Threading;
  34. namespace MyEventLog
  35. {
  36. /// <summary>
  37. /// 事件日志记录类,提供事件日志记录支持 
  38. /// <remarks>
  39. /// 定义了4个日志记录方法 (error, warning, info, trace) 
  40. /// </remarks>
  41. /// </summary>
  42. public class ApplicationLog
  43. {
  44.     /// <summary>
  45.     /// 将错误信息记录到Win2000/NT事件日志中
  46.     /// <param name="message">需要记录的文本信息</param>
  47.     /// </summary>
  48.     public static void WriteError(String message){
  49.         WriteLog(TraceLevel.Error, message);
  50.     }
  51.     /// <summary>
  52.     /// 将警告信息记录到Win2000/NT事件日志中
  53.     /// <param name="message">需要记录的文本信息</param>
  54.     /// </summary>
  55.     public static void WriteWarning(String message){
  56.         WriteLog(TraceLevel.Warning, message);
  57.     }
  58.     /// <summary>
  59.     /// 将提示信息记录到Win2000/NT事件日志中
  60.     /// <param name="message">需要记录的文本信息</param>
  61.     /// </summary>
  62.     public static void WriteInfo(String message){
  63.         WriteLog(TraceLevel.Info, message);
  64.     }
  65.     /// <summary>
  66.     /// 将跟踪信息记录到Win2000/NT事件日志中
  67.     /// <param name="message">需要记录的文本信息</param>
  68.     /// </summary>
  69.     public static void WriteTrace(String message){
  70.         WriteLog(TraceLevel.Verbose, message);
  71.     }
  72.     /// <summary>
  73.     /// 格式化记录到事件日志的文本信息格式
  74.     /// <param name="ex">需要格式化的异常对象</param>
  75.     /// <param name="catchInfo">异常信息标题字符串.</param>
  76.     /// <retvalue>
  77.     /// <para>格式后的异常信息字符串,包括异常内容和跟踪堆栈.</para>
  78.     /// </retvalue>
  79.     /// </summary>
  80.     public static String FormatException(Exception ex, String catchInfo){
  81.         StringBuilder strBuilder = new StringBuilder();
  82.         if (catchInfo != String.Empty){
  83.             strBuilder.Append(catchInfo).Append("/r/n");
  84.         }
  85.         strBuilder.Append(ex.Message).Append("/r/n").Append(ex.StackTrace);
  86.         return strBuilder.ToString();
  87.     }
  88.     /// <summary>
  89.     /// 实际事件日志写入方法
  90.     /// <param name="level">要记录信息的级别(error,warning,info,trace).</param>
  91.     /// <param name="messageText">要记录的文本.</param>
  92.     /// </summary>
  93.     private static void WriteLog(TraceLevel level, String messageText){
  94.         try
  95.         EventLogEntryType LogEntryType;
  96.         switch (level)
  97.         {
  98.             case TraceLevel.Error:
  99.                 LogEntryType = EventLogEntryType.Error;
  100.                 break;
  101.             case TraceLevel.Warning:
  102.                 LogEntryType = EventLogEntryType.Warning;
  103.                 break;
  104.             case TraceLevel.Info:
  105.                 LogEntryType = EventLogEntryType.Information;
  106.                 break;
  107.             case TraceLevel.Verbose:
  108.                 LogEntryType = EventLogEntryType.SuccessAudit;
  109.                 break;
  110.             default:
  111.                 LogEntryType = EventLogEntryType.SuccessAudit;
  112.                 break;
  113.             }
  114.             EventLog eventLog = new EventLog("Application", ApplicationConfiguration.EventLogMachineName, ApplicationConfiguration.EventLogSourceName );
  115.             //写入事件日志
  116.             eventLog.WriteEntry(messageText, LogEntryType);
  117.         }
  118.         catch {} //忽略任何异常
  119.         } 
  120.     } //class ApplicationLog
  121. }

7.Panel 横向滚动,纵向自动扩展

  1. <asp:panel style="overflow-x:scroll;overflow-y:auto;"></asp:panel>

8.回车转换成Tab

(1)

  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>

(2)当在有keydown事件的控件上敲回车时,变为tab

  1. public void Tab(System.Web .UI.WebControls .WebControl webcontrol) { 
  2.         webcontrol.Attributes .Add ("onkeydown""if(event.keyCode==13) event.keyCode=9"); 
  3.  

9.DataGrid超级连接列

  1. DataNavigateUrlField="字段名"DataNavigateUrlFormatString="http://xx/inc/delete.aspx?ID={0}"

10.DataGrid行随鼠标变色

  1. private void DGzf_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e){
  2.     if (e.Item.ItemType!=ListItemType.Header){
  3.         e.Item.Attributes.Add( "onmouseout","this.style.backgroundColor=/""+e.Item.Style["BACKGROUND-COLOR"]+"/"");
  4.         e.Item.Attributes.Add( "onmouseover","this.style.backgroundColor=/"""#EFF3F7"+"/"");
  5.     }
  6. }

11.模板列

  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. <ASP:TEMPLATECOLUMN headertext="选中">
  7. <HEADERSTYLE wrap="False" horiz></HEADERSTYLE>
  8. <ITEMTEMPLATE>
  9. <ASP:CHECKBOX id="chkExport" runat="server" />
  10. </ITEMTEMPLATE>
  11. <EDITITEMTEMPLATE>
  12. <ASP:CHECKBOX id="chkExportON" runat="server" enabled="true" />
  13. </EDITITEMTEMPLATE>
  14. </ASP:TEMPLATECOLUMN>

后台代码

  1. protected void CheckAll_CheckedChanged(object sender, System.EventArgs e)
  2. {
  3.     //改变列的选定,实现全选或全不选。
  4.     CheckBox chkExport ;
  5.     if( CheckAll.Checked){
  6.         foreach(DataGridItem oDataGridItem in MyDataGrid.Items)
  7.         {
  8.             chkExport = (CheckBox)oDataGridItem.FindControl("chkExport");
  9.             chkExport.Checked = true;
  10.         }
  11.     }
  12.     else
  13.     {
  14.         foreach(DataGridItem oDataGridItem in MyDataGrid.Items)
  15.         {
  16.             chkExport = (CheckBox)oDataGridItem.FindControl("chkExport");
  17.             chkExport.Checked = false;
  18.         }
  19.     }
  20. }

12.数字格式化

  1. <%#Container.DataItem("price")%>//的结果是500.0000,怎样格式化为500.00?
  2. <%#Container.DataItem("price","{0:¥#,##0.00}")%>
  3. int i=123456;
  4. string s=i.ToString("###,###.00"); 

13.日期格式化

  1. //aspx页面内:
  2. <%# DataBinder.Eval(Container.DataItem,"Company_Ureg_Date")%>
  3. //显示为: 2004-8-11 19:44:28
  4. //我只想要:2004-8-11
  5. <%# DataBinder.Eval(Container.DataItem,"Company_Ureg_Date","{0:yyyy-M-d}")%>
  6. //应该如何改?
  7. //格式化日期
  8. //取出来,一般是
  9. object((DateTime)objectFromDB).ToString("yyyy-MM-dd");

【日期的验证表达式】

A.以下正确的输入格式:
[2004-2-29], [2004-02-29 10:29:39 pm], [2004/12/31]

^((/d{2}(([02468][048])|([13579][26]))[/-///s]?((((0?[13578])|(1[02]))[/-///s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[/-///s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[/-///s]?((0?[1-9])|([1-2][0-9])))))|(/d{2}(([02468][1235679])|([13579][01345789]))[/-///s]?((((0?[13578])|(1[02]))[/-///s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[/-///s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[/-///s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(/s(((0?[1-9])|(1[0-2]))/:([0-5][0-9])((/s)|(/:([0-5][0-9])/s))([AM|PM|am|pm]{2,2})))?$

 

B.以下正确的输入格式:
[0001-12-31], [9999 09 30], [2002/03/03]

^/d{4}[/-///s]?((((0[13578])|(1[02]))[/-///s]?(([0-2][0-9])|(3[01])))|(((0[469])|(11))[/-///s]?(([0-2][0-9])|(30)))|(02[/-///s]?[0-2][0-9]))$

【大小写转换】

  1. HttpUtility.HtmlEncode(string);
  2. HttpUtility.HtmlDecode(string);

14.如何设定全局变量

Global.asax中

Application_Start()事件中

添加

  1. Application[属性名] = xxx;

就是你的全局变量

15.怎样作到HyperLinkColumn生成的连接后,点击连接,打开新窗口?

HyperLinkColumn有个属性Target,将器值设置成"_blank"即可.(Target="_blank")

【ASPNETMENU】点击菜单项弹出新窗口

在你的menuData.xml文件的菜单项中加入URLTarget="_blank",如:

  1. <?xml version="1.0" encoding="GB2312"?>
  2. <MenuData ImagesBaseURL="images/"> 
  3. <MenuGroup>
  4. <MenuItem Label="内参信息" URL="Infomation.aspx" >
  5. <MenuGroup ID="BBC">
  6. <MenuItem Label="公告信息" URL="Infomation.aspx" URLTarget="_blank" LeftIcon="file.gif"/>
  7. <MenuItem Label="编制信息简报" URL="NewInfo.aspx" LeftIcon="file.gif" />

最好将你的aspnetmenu升级到1.2版。