asp.net

Asp.net非常实用的51个代码(1)

2013-08-28

1.//弹出对话框.点击转向指定页面

  1. Response.Write(&quot;<script>window.alert('该会员没有提交申请,请重新提交!')</script>&quot;);

  2. Response.Write(&quot;<script>window.location ='http://www.51aspx.com/bizpulic/upmeb.aspx'</script>&quot;);
复制代码

2.//弹出对话框

  1. Response.Write(&quot;<script language='javascript'>alert('产品添加成功!')</script >&quot;);
复制代码

3.//删除文件

  1. string filename =&quot;20059595157517.jpg&quot;;

  2. pub.util.DeleteFile(HttpContext.Current.Server.MapPath(&quot;../file/&quot;)+filename);
复制代码

4.//绑定下拉列表框datalist

  1. System.Data.DataView dv=conn.Exec_ex(&quot;Select -1 as code,'请选择经营模式' as content from dealin union Select code,content from dealin&quot;);

  2. this.dealincode.DataSource=dv;

  3. this.dealincode.DataTextField=&quot;content&quot;;

  4. this.dealincode.DataValueField=&quot;code&quot;;    

  5. this.dealincode.DataBind();

  6. this.dealincode.Items.FindByValue(dv[0][&quot;dealincode&quot;].ToString()).Selected=true;
复制代码

5.//时间去秒显示

  1. <%# System.DateTime.Parse(DataBinder.Eval(Container.DataItem,&quot;begtime&quot;).ToString()).ToShortDateString()%>
复制代码

6.//标题带链接

  1. <%# &quot;<a class=\&quot;12c\&quot; target=\&quot;_blank\&quot; href=\&quot;http://www.51aspx/CV/_&quot;+DataBinder.Eval(Container.DataItem,&quot;procode&quot;)+&quot;.html\&quot;>&quot;+ DataBinder.Eval(Container.DataItem,&quot;proname&quot;)+&quot;</a>&quot;%>
复制代码

7.//修改转向

  1. <%# &quot;<A href=\&quot;editpushpro.aspx?id=&quot;+DataBinder.Eval(Container.DataItem,&quot;code&quot;)+&quot;\&quot;>&quot;+&quot;修改&quot;+&quot;</A>&quot;%>
复制代码

8.//弹出确定按钮

  1. <%# &quot;<A id=\&quot;btnDelete\&quot; onclick=\&quot;return confirm('你是否确定删除这条记录吗?');\&quot; href=\&quot;pushproduct.aspx?dl=&quot;+DataBinder.Eval(Container.DataItem,&quot;code&quot;)+&quot;\&quot;>&quot;+&quot;删除&quot;+&quot;</A>&quot;%>
复制代码

9.//输出数据格式化 "{0:F2}" 是格式 F2表示小数点后剩两位

  1. <%# DataBinder.Eval(Container, &quot;DataItem.PriceMoney&quot;,&quot;{0:F2}&quot;) %>
复制代码

10.//提取动态网页内容

  1. Uri uri = new Uri(&quot;http://www.51aspx.com/&quot;);

  2.    WebRequest req = WebRequest.Create(uri);

  3.    WebResponse resp = req.GetResponse();

  4.    Stream str = resp.GetResponseStream();

  5.    StreamReader sr = new StreamReader(str,System.Text.Encoding.Default);

  6.    string t = sr.ReadToEnd();

  7.    this.Response.Write(t.ToString());
复制代码

11.//获取" . "后面的字符

  1. i.ToString().Trim().Substring(i.ToString().Trim().LastIndexOf(&quot;.&quot;)+1).ToLower().Trim()
复制代码

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

  1. response.write(&quot;<script>window.open(’×.aspx?id=&quot;+this.DropDownList1.SelectIndex+&quot;&amp;id1=&quot;+...+&quot;’)</script>&quot;)
复制代码

接收参数:

  1. string a = Request.QueryString(&quot;id&quot;);

  2. string b = Request.QueryString(&quot;id1&quot;);
复制代码

12.为按钮添加对话框

  1. Button1.Attributes.Add(&quot;onclick&quot;,&quot;return confirm(’确认?’)&quot;);

  2. button.attributes.add(&quot;onclick&quot;,&quot;if(confirm(’are you sure...?’)){return true;}else{return false;}&quot;)
复制代码

13.删除表格选定记录

  1. int intEmpID = (int)MyDataGrid.DataKeys[e.Item.ItemIndex];

  2. string deleteCmd = &quot;Delete from Employee where emp_id = &quot; + intEmpID.ToString()
复制代码

14.删除表格记录警告

  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(&quot;onclick&quot;,&quot;return confirm(’您是否确定要删除这条信息’);&quot;);

  13.    break;

  14.   default:

  15.    break;

  16.  }

  17. }
复制代码

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

  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(&quot;onclick&quot;,&quot;window.open(’Default.aspx?id=&quot; + e.Item.Cells[0].Text + &quot;’);&quot;);

  6. }
复制代码

双击表格连接到另一页  在itemDataBind事件中

  1. if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)

  2. {

  3.  string orderItemID =e.item.cells[1].Text;

  4.  e.item.Attributes.Add(&quot;ondblclick&quot;, &quot;location.href=’../ShippedGrid.aspx?id=&quot; + orderItemID + &quot;’&quot;);

  5. }
复制代码

双击表格打开新一页

  1. if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)

  2. {

  3.  string orderItemID =e.item.cells[1].Text;

  4.  e.item.Attributes.Add(&quot;ondblclick&quot;, &quot;open(’../ShippedGrid.aspx?id=&quot; + orderItemID + &quot;’)&quot;);

  5. }
复制代码

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

  1. <asp:HyperLinkColumn Target=&quot;_blank&quot; headertext=&quot;ID号&quot; DataTextField=&quot;id&quot; NavigateUrl=&quot;aaa.aspx?id=’

  2.  <%# DataBinder.Eval(Container.DataItem, &quot;数据字段1&quot;)%>’ &amp; name=’<%# DataBinder.Eval(Container.DataItem, &quot;数据字段2&quot;)%>’ />
复制代码

17.表格点击改变颜色

  1. if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem)

  2. {

  3.  e.Item.Attributes.Add(&quot;onclick&quot;,&quot;this.style.backgroundColor=’#99cc00’;

  4.     this.style.color=’buttontext’;this.style.cursor=’default’;&quot;);

  5. }
复制代码

写在DataGrid的_ItemDataBound里

  1. if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem)

  2. {

  3. e.Item.Attributes.Add(&quot;onmouseover&quot;,&quot;this.style.backgroundColor=’#99cc00’;

  4.    this.style.color=’buttontext’;this.style.cursor=’default’;&quot;);

  5. e.Item.Attributes.Add(&quot;onmouseout&quot;,&quot;this.style.backgroundColor=’’;this.style.color=’’;&quot;);

  6. }
复制代码

18.关于日期格式  日期格式设定 DataFormatString="{0:yyyy-MM-dd}"   我觉得应该在itembound事件中 e.items.cell["你的列"].text=DateTime.Parse(e.items.cell["你的列"].text.ToString("yyyy-MM-dd")) 19.获取错误信息并到指定页面不要使用Response.Redirect,而应该使用Server.Transfer   e.g

  1. // in global.asax

  2. protected void Application_Error(Object sender, EventArgs e) {

  3. if (Server.GetLastError() is HttpUnhandledException)

  4. Server.Transfer(&quot;MyErrorPage.aspx&quot;);
复制代码

//其余的非HttpUnhandledException异常交给ASP.NET自己处理就okay了 :) }   Redirect会导致post-back的产生从而丢失了错误信息,所以页面导向应该直接在服务器端执行,这样就可以在错误处理页面得到出错信息并进行相应的处理 20.清空Cookie

  1. Cookie.Expires=[DateTime];

  2. Response.Cookies(&quot;UserName&quot;).Expires = 0
复制代码

21.自定义异常处理

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

  14.    if (ApplicationConfiguration.EventLogEnabled)LogEvent(&quot;出现一个未知错误。&quot;);

  15.   }

  16.  public AppException(string message)

  17.  {

  18.   LogEvent(message);

  19.  }

  20.  public AppException(string message,Exception innerException)

  21.  {

  22.   LogEvent(message);

  23.   if (innerException != null)

  24.   {

  25.    LogEvent(innerException.Message);

  26.   }

  27.  }

  28.  //日志记录类

  29.  using System;

  30.  using System.Configuration;

  31.  using System.Diagnostics;

  32.  using System.IO;

  33.  using System.Text;

  34.  using System.Threading;

  35.  namespace MyEventLog

  36.  {

  37.   /// <summary>

  38.   /// 事件日志记录类,提供事件日志记录支持

  39.   /// <remarks>

  40.   /// 定义了4个日志记录方法 (error, warning, info, trace)

  41.   /// </remarks>

  42.   /// </summary>

  43.   public class ApplicationLog

  44.   {

  45.    /// <summary>

  46.    /// 将错误信息记录到Win2000/NT事件日志中

  47.    /// <param name=&quot;message&quot;>需要记录的文本信息</param>

  48.    /// </summary>

  49.    public static void WriteError(String message)

  50.    {

  51.     WriteLog(TraceLevel.Error, message);

  52.    }

  53.    /// <summary>

  54.    /// 将警告信息记录到Win2000/NT事件日志中

  55.    /// <param name=&quot;message&quot;>需要记录的文本信息</param>

  56.    /// </summary>

  57.    public static void WriteWarning(String message)

  58.    {

  59.     WriteLog(TraceLevel.Warning, message);  

  60.    }

  61.    /// <summary>

  62.    /// 将提示信息记录到Win2000/NT事件日志中

  63.    /// <param name=&quot;message&quot;>需要记录的文本信息</param>

  64.    /// </summary>

  65.    public static void WriteInfo(String message)

  66.    {

  67.     WriteLog(TraceLevel.Info, message);

  68.    }

  69.    /// <summary>

  70.    /// 将跟踪信息记录到Win2000/NT事件日志中

  71.    /// <param name=&quot;message&quot;>需要记录的文本信息</param>

  72.    /// </summary>

  73.    public static void WriteTrace(String message)

  74.    {

  75.     WriteLog(TraceLevel.Verbose, message);

  76.    }

  77.    /// <summary>

  78.    /// 格式化记录到事件日志的文本信息格式

  79.    /// <param name=&quot;ex&quot;>需要格式化的异常对象</param>

  80.    /// <param name=&quot;catchInfo&quot;>异常信息标题字符串.</param>

  81.    /// <retvalue>

  82.    /// <para>格式后的异常信息字符串,包括异常内容和跟踪堆栈.</para>

  83.    /// </retvalue>

  84.    /// </summary>

  85.    public static String FormatException(Exception ex, String catchInfo)

  86.    {

  87.     StringBuilder strBuilder = new StringBuilder();

  88.     if (catchInfo != String.Empty)

  89.     {

  90.      strBuilder.Append(catchInfo).Append(&quot;\r\n&quot;);

  91.     }

  92.     strBuilder.Append(ex.Message).Append(&quot;\r\n&quot;).Append(ex.StackTrace);

  93.     return strBuilder.ToString();

  94.    }

  95.    /// <summary>

  96.    /// 实际事件日志写入方法

  97.    /// <param name=&quot;level&quot;>要记录信息的级别(error,warning,info,trace).</param>

  98.    /// <param name=&quot;messageText&quot;>要记录的文本.</param>

  99.    /// </summary>

  100.    private static void WriteLog(TraceLevel level, String messageText)

  101.    {

  102.     try

  103.     {

  104.      EventLogEntryType LogEntryType;

  105.      switch (level)

  106.      {

  107.       case TraceLevel.Error:

  108.        LogEntryType = EventLogEntryType.Error;

  109.        break;

  110.       case TraceLevel.Warning:

  111.        LogEntryType = EventLogEntryType.Warning;

  112.        break;

  113.       case TraceLevel.Info:

  114.        LogEntryType = EventLogEntryType.Information;

  115.        break;

  116.       case TraceLevel.Verbose:

  117.        LogEntryType = EventLogEntryType.SuccessAudit;

  118.        break;

  119.       default:

  120.        LogEntryType = EventLogEntryType.SuccessAudit;

  121.        break;

  122.      }

  123.      EventLog eventLog = new EventLog(&quot;Application&quot;, ApplicationConfiguration.EventLogMachineName, ApplicationConfiguration.EventLogSourceName );

  124.      //写入事件日志

  125.      eventLog.WriteEntry(messageText, LogEntryType);

  126.     }

  127.    catch {} //忽略任何异常

  128.   }

  129.  } //class ApplicationLog

  130. }
复制代码

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

  1. <asp:panel style=&quot;overflow-x:scroll;overflow-y:auto;&quot;></asp:panel>
复制代码

23.回车转换成Tab (1)

  1. <script language=&quot;javascript&quot; for=&quot;document&quot; event=&quot;onkeydown&quot;>

  2.  if(event.keyCode==13 &amp;&amp; event.srcElement.type!=’button’ &amp;&amp; event.srcElement.type!=’submit’ &amp;&amp;     event.srcElement.type!=’reset’ &amp;&amp; event.srcElement.type!=’’&amp;&amp; event.srcElement.type!=’textarea’);

  3.    event.keyCode=9;

  4. </script>
复制代码

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

  1. public void Tab(System.Web .UI.WebControls .WebControl webcontrol)

  2. {

  3. webcontrol.Attributes .Add (&quot;onkeydown&quot;, &quot;if(event.keyCode==13) event.keyCode=9&quot;);

  4. }

  5. 24.DataGrid超级连接列

  6. DataNavigateUrlField=&quot;字段名&quot; DataNavigateUrlFormatString=&quot;http://xx/inc/delete.aspx?ID={0}&quot;
复制代码

25.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( &quot;onmouseout&quot;,&quot;this.style.backgroundColor=\&quot;&quot;+e.Item.Style[&quot;BACKGROUND-COLOR&quot;]+&quot;\&quot;&quot;);

  6.   e.Item.Attributes.Add( &quot;onmouseover&quot;,&quot;this.style.backgroundColor=\&quot;&quot;+ &quot;#EFF3F7&quot;+&quot;\&quot;&quot;);

  7.  }

  8. }
复制代码

26.模板列

  1. <ASP:TEMPLATECOLUMN visible=&quot;False&quot; sortexpression=&quot;demo&quot; headertext=&quot;ID&quot;>

  2. <ITEMTEMPLATE>

  3. <ASP LABEL text=’<%# DataBinder.Eval(Container.DataItem, &quot;ArticleID&quot;)%>’ runat=&quot;server&quot; width=&quot;80%&quot; id=&quot;lblColumn&quot; />

  4. </ITEMTEMPLATE>

  5. </ASP:TEMPLATECOLUMN>

  6. <ASP:TEMPLATECOLUMN headertext=&quot;选中&quot;>

  7. <HEADERSTYLE wrap=&quot;False&quot; horiz></HEADERSTYLE>

  8. <ITEMTEMPLATE>

  9. <ASP:CHECKBOX id=&quot;chkExport&quot; runat=&quot;server&quot; />

  10. </ITEMTEMPLATE>

  11. <EDITITEMTEMPLATE>

  12. <ASP:CHECKBOX id=&quot;chkExportON&quot; runat=&quot;server&quot; enabled=&quot;true&quot; />

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

  7.   foreach(DataGridItem oDataGridItem in MyDataGrid.Items)

  8.   {

  9.    chkExport = (CheckBox)oDataGridItem.FindControl(&quot;chkExport&quot;);

  10.    chkExport.Checked = true;

  11.   }

  12.  }

  13.  else

  14.  {

  15.   foreach(DataGridItem oDataGridItem in MyDataGrid.Items)

  16.   {

  17.    chkExport = (CheckBox)oDataGridItem.FindControl(&quot;chkExport&quot;);

  18.    chkExport.Checked = false;

  19.   }

  20.  }

  21. }
复制代码

27.数字格式化

  1. 【<%#Container.DataItem(&quot;price&quot;)%>的结果是500.0000,怎样格式化为500.00?】

  2. <%#Container.DataItem(&quot;price&quot;,&quot;{0:¥#,##0.00}&quot;)%>

  3. int i=123456;

  4. string s=i.ToString(&quot;###,###.00&quot;);