• ASPNET程序中常用的三十三种代码


    1. 打开新的窗口并传送参数

    1. response.write("<script>window.open(’*.aspx?id="+this.DropDownList1.SelectIndex+"&id1="+...+"’)</script>") 
    2.   接收参数: 
    3. string a = Request.QueryString("id"); 
    4. string b = Request.QueryString("id1");

    2.为按钮添加对话框

    1. Button1.Attributes.Add("onclick","return confirm(’确认?’)"); 
    2. 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.   switch(e.Item.ItemType) 
    3.   { 
    4.   case ListItemType.Item : 
    5.   case ListItemType.AlternatingItem : 
    6.   case ListItemType.EditItem: 
    7.   TableCell myTableCell; 
    8.   myTableCell = e.Item.Cells[14]; 
    9.   LinkButton myDeleteButton ; 
    10.   myDeleteButton = (LinkButton)myTableCell.Controls[0]; 
    11.   myDeleteButton.Attributes.Add("onclick","return confirm(’您是否确定要删除这条信息’);"); 
    12.   break; 
    13.   default: 
    14.   break; 
    15.   } 
    16. }

    5.点击表格行链接另一页 

    1. private void grdCustomer_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) 
    2.   //点击表格打开 
    3.   if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
    4.   e.Item.Attributes.Add("onclick","window.open(’Default.aspx?id=" + e.Item.Cells[0].Text + "’);");
    5.   双击表格连接到另一页 
    6.   在itemDataBind事件中 
    7. if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
    8.   string orderItemID =e.item.cells[1].Text; 
    9.   ... 
    10.   e.item.Attributes.Add("ondblclick", "location.href=’../ShippedGrid.aspx?id=" + orderItemID + "’"); 
    11.   双击表格打开新一页 
    12. if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
    13.   string orderItemID =e.item.cells[1].Text; 
    14.   ... 
    15.   e.item.Attributes.Add("ondblclick", "open(’../ShippedGrid.aspx?id=" + orderItemID + "’)"); 
    16. }

    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.   e.Item.Attributes.Add("onclick","this.style.backgroundColor=’#99cc00’; 
    3.     this.style.color=’buttontext’;this.style.cursor=’default’;"); 
    4.   写在DataGrid的_ItemDataBound里 
    5. if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem) 
    6. e.Item.Attributes.Add("onmouseover","this.style.backgroundColor=’#99cc00’; 
    7.   this.style.color=’buttontext’;this.style.cursor=’default’;"); 
    8. e.Item.Attributes.Add("onmouseout","this.style.backgroundColor=’’;this.style.color=’’;"); 

    8.关于日期格式

    1. 日期格式设定 
    2. DataFormatString="{0:yyyy-MM-dd}" 
    3.   我觉得应该在itembound事件中 
    4. e.items.cell["你的列"].text=DateTime.Parse(e.items.cell["你的列"].text.ToString("yyyy-MM-dd"))

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

    1. 不要使用Response.Redirect,而应该使用Server.Transfer 
    2.   e.g 
    3. // in global.asax 
    4. protected void Application_Error(Object sender, EventArgs e) { 
    5. if (Server.GetLastError() is HttpUnhandledException) 
    6. Server.Transfer("MyErrorPage.aspx"); 
    7. //其余的非HttpUnhandledException异常交给ASP.NET自己处理就okay了 :) 
    8. }

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

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

    <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. onkeydown="if(event.keyCode==13) event.keyCode=9"

    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.   if (e.Item.ItemType!=ListItemType.Header) 
    3.   { 
    4.   e.Item.Attributes.Add( "onmouseout","this.style.backgroundColor=""+e.Item.Style["BACKGROUND-COLOR"]+"""); 
    5.   e.Item.Attributes.Add( "onmouseover","this.style.backgroundColor=""+ "#EFF3F7"+"""); 
    6.   } 

    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. <ASP:TEMPLATECOLUMN headertext="选中"> 
    7. <HEADERSTYLE wrap="False" horizontalalign="Center"></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> 
    15.   后台代码 
    16. protected void CheckAll_CheckedChanged(object sender, System.EventArgs e) 
    17.   //改变列的选定,实现全选或全不选。 
    18.   CheckBox chkExport ; 
    19.   if( CheckAll.Checked) 
    20.   { 
    21.   foreach(DataGridItem oDataGridItem in MyDataGrid.Items) 
    22.   { 
    23.   chkExport = (CheckBox)oDataGridItem.FindControl("chkExport"); 
    24.   chkExport.Checked = true; 
    25.   } 
    26.   } 
    27.   else 
    28.   { 
    29.   foreach(DataGridItem oDataGridItem in MyDataGrid.Items) 
    30.   { 
    31.   chkExport = (CheckBox)oDataGridItem.FindControl("chkExport"); 
    32.   chkExport.Checked = false; 
    33.   } 
    34.   } 
    35. }

    17.数字格式化

    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");

    18.日期格式化

    【aspx页面内:<%# DataBinder.Eval(Container.DataItem,"Company_Ureg_Date")%>
    显示为: 2004-8-11 19:44:28
    我只想要:2004-8-11 】

    <%# DataBinder.Eval(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] 

    ^((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]))$ 


    【大小写转换】

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

    19.如何设定全局变量
    Global.asax中

    Application_Start()事件中

    添加Application[属性名] = xxx;

    就是你的全局变量

    20.怎样作到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" />
    8. ......
    21.委托讨论
    1. [url]http://community.csdn.net/Expert/topic/2651/2651579.xml?temp=.7183191[/url]
    2. [url]http://dev.csdn.net/develop/article/22/22951.shtm[/url]
    22.读取DataGrid控件TextBox值
    1. foreach(DataGrid dgi in yourDataGrid.Items)
    2. {
    3. TextBox tb = (TextBox)dgi.FindControl("yourTextBoxId");
    4. tb.Text....
    5. }
  • 相关阅读:
    教你一招用 IDE 编程提升效率的骚操作!
    动态拼接sql语句工具类
    mysql数据建模规范
    分割字符串为数字列表
    linux 配置mysql odbc
    nodejs npm常用命令
    (四)jquery easyui panel window使用
    (三)jquery easyui常用form控件的使用
    (二)jquery easyUI提示框的使用
    (一)jQuery easyUI 环境的搭建
  • 原文地址:https://www.cnblogs.com/lzh007blog/p/3522930.html
Copyright © 2020-2023  润新知