星空网 > 软件开发 > ASP.net

Asp.net常用的51个代码

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

28.日期格式化【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) 29.如何设定全局变量Global.asax中Application_Start()事件中添加Application[属性名] = xxx; 就是你的全局变量 30.怎样作到HyperLinkColumn生成的连接后,点击连接,打开新窗口?HyperLinkColumn有个属性Target,将器值设置成"_blank"即可.(Target="_blank") 【ASPNETMENU】点击菜单项弹出新窗口在你的menuData.

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

最好将你的aspnetmenu升级到1.2版 31.读取DataGrid控件TextBox值

  1. foreach(DataGrid dgi in yourDataGrid.Items)
  2. {
  3. TextBox tb = (TextBox)dgi.FindControl(&quot;yourTextBoxId&quot;);
  4. tb.Text....
  5. }

33.在DataGrid中有3个模板列包含Textbox分别为 DG_ShuLiang (数量) DG_DanJian(单价) DG_JinE(金额)分别在5.6.7列,要求在录入数量及单价的时候自动算出金额即:数量*单价=金额还要求录入时限制为 数值型.我如何用客户端脚本实现这个功能?

  1. <asp:TemplateColumn HeaderText=&quot;数量&quot;>
  2. <ItemTemplate>
  3. <asp:TextBox id=&quot;ShuLiang&quot; runat=’server’ Text=’<%# DataBinder.Eval(Container.DataItem,&quot;DG_ShuLiang&quot;)%>’
  4.  
  5. />
  6. <asp:RegularExpressionValidator id=&quot;revS&quot; runat=&quot;server&quot; C ErrorMessage=&quot;must be integer&quot; Validati />
  7. </ItemTemplate>
  8. </asp:TemplateColumn>
  9. <asp:TemplateColumn HeaderText=&quot;单价&quot;>
  10. <ItemTemplate>
  11. <asp:TextBox id=&quot;DanJian&quot; runat=’server’ Text=’<%# DataBinder.Eval(Container.DataItem,&quot;DG_DanJian&quot;)%>’
  12.  
  13. />
  14. <asp:RegularExpressionValidator id=&quot;revS2&quot; runat=&quot;server&quot; C ErrorMessage=&quot;must be numeric&quot; Validati />
  15. </ItemTemplate>
  16. </asp:TemplateColumn>
  17. <asp:TemplateColumn HeaderText=&quot;金额&quot;>
  18. <ItemTemplate>
  19. <asp:TextBox id=&quot;JinE&quot; runat=’server’ Text=’<%# DataBinder.Eval(Container.DataItem,&quot;DG_JinE&quot;)%>’ />
  20. </ItemTemplate>
  21. </asp:TemplateColumn><script language=&quot;javascript&quot;>
  22. function DoCal()
  23. {
  24. var e = event.srcElement;
  25. var row = e.parentNode.parentNode;
  26. var txts = row.all.tags(&quot;INPUT&quot;);
  27. if (!txts.length || txts.length < 3)
  28. return;
  29. var q = txts[txts.length-3].value;
  30. var p = txts[txts.length-2].value;
  31. if (isNaN(q) || isNaN(p))
  32. return;
  33. q = parseInt(q);
  34. p = parseFloat(p);
  35. txts[txts.length-1].value = (q * p).toFixed(2);
  36. }
  37. </script>

34.datagrid选定比较底下的行时,为什么总是刷新一下,然后就滚动到了最上面,刚才选定的行因屏幕的关系就看不到了。 page_load page.smartNavigation=true 35.在Datagrid中修改数据,当点击编辑键时,数据出现在文本框中,怎么控制文本框的大小 ?

  1. private void DataGrid1_ItemDataBound(obj sender,DataGridItemEventArgs e)
  2. {
  3. for(int i=0;i<e.Item.Cells.Count-1;i++)
  4. if(e.Item.ItemType==ListItemType.EditType)
  5. {
  6. e.Item.Cells.Attributes.Add(&quot;Width&quot;, &quot;80px&quot;)
  7. }
  8. }

36.对话框

  1. private static string ScriptBegin = &quot;<script language=\&quot;JavaScript\&quot;>&quot;;
  2. private static string ScriptEnd = &quot;</script>&quot;;
  3. public static void ConfirmMessageBox(string PageTarget,string Content)
  4. {
  5. string C+Content+&quot;’);&quot;+&quot;if(retValue){window.location=’&quot;+PageTarget+&quot;’;}&quot;;
  6. ConfirmContent=ScriptBegin + ConfirmContent + ScriptEnd;
  7. Page ParameterPage = (Page)System.Web.HttpContext.Current.Handler;
  8. ParameterPage.RegisterStartupScript(&quot;confirm&quot;,ConfirmContent);
  9. //Response.Write

复制代码

(strScript); } 37. 将时间格式化:string aa=DateTime.Now.ToString("yyyyMMdd"); 1.1 取当前年月日时分秒 currentTime=System.DateTime.Now; 1.2 取当前年 int = DateTime.Now.Year; 1.3 取当前月 int = DateTime.Now.Month; 1.4 取当前日 int = DateTime.Now.Day; 1.5 取当前时 int = DateTime.Now.Hour; 1.6 取当前分 int = DateTime.Now.Minute; 1.7 取当前秒 int = DateTime.Now.Second; 1.8 取当前毫秒 int 毫秒= DateTime.Now.Millisecond; 38.自定义分页代码:先定义变量 

  1. public static int pageCount; //总页面数
  2. public static int curPageIndex=1; //当前页面
  3. 下一页:
  4. if(DataGrid1.CurrentPageIndex < (DataGrid1.PageCount - 1))
  5. {
  6. DataGrid1.CurrentPageIndex += 1;
  7. curPageIndex+=1;
  8. }
  9. bind(); // DataGrid1数据绑定函数
  10. 上一页:
  11. if(DataGrid1.CurrentPageIndex >0)
  12. {
  13. DataGrid1.CurrentPageIndex += 1;
  14. curPageIndex-=1;
  15. }
  16. bind(); // DataGrid1数据绑定函数
  17. 直接页面跳转:
  18. int a=int.Parse(JumpPage.Value.Trim());//JumpPage.Value.Trim()为跳转值
  19. if(a<DataGrid1.PageCount)
  20. {
  21. this.DataGrid1.CurrentPageIndex=a;
  22. }
  23. bind();

39DataGrid使用: 添加删除确认:

  1. private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
  2. {
  3. foreach(DataGridItem di in this.DataGrid1.Items)
  4. {
  5. if(di.ItemType==ListItemType.Item||di.ItemType==ListItemType.AlternatingItem)
  6. {
  7. ((LinkButton)di.Cells[8].Controls[0]).Attributes.Add(&quot;onclick&quot;,&quot;return confirm(’确认删除此项吗?’);&quot;);
  8. }
  9. }
  10. }

样式交替:

  1. ListItemType itemType = e.Item.ItemType;
  2. if (itemType == ListItemType.Item )
  3. {
  4. e.Item.Attributes[&quot;onmouseout&quot;] = &quot;javascript:this.style.backgroundColor=’#FFFFFF’;&quot;;
  5. e.Item.Attributes[&quot;onmouseover&quot;] = &quot;javascript:this.style.backgroundColor=’#d9ece1’;cursor=’hand’;&quot; ;
  6. }
  7. else if( itemType == ListItemType.AlternatingItem)
  8. {
  9. e.Item.Attributes[&quot;onmouseout&quot;] = &quot;javascript:this.style.backgroundColor=’#a0d7c4’;&quot;;
  10. e.Item.Attributes[&quot;onmouseover&quot;] = &quot;javascript:this.style.backgroundColor=’#d9ece1’;cursor=’hand’;&quot; ;
  11. }

添加一个编号列:

  1. DataTable dt= c.ExecuteRtnTableForAccess(sqltxt); //执行sql返回的DataTable
  2. DataColumn dc=dt.Columns.Add(&quot;number&quot;,System.Type.GetType(&quot;System.String&quot;));
  3. for(int i=0;i<dt.Rows.Count;i++)
  4. {
  5. dt.Rows[&quot;number&quot;]=(i+1).ToString();
  6. }
  7. DataGrid1.DataSource=dt;
  8. DataGrid1.DataBind();
  9. DataGrid1中添加一个CheckBox,页面中添加一个全选框
  10. private void CheckBox2_CheckedChanged(object sender, System.EventArgs e)
  11. {
  12. foreach(DataGridItem thisitem in DataGrid1.Items)
  13. {
  14. ((CheckBox)thisitem.Cells[0].Controls[1]).Checked=CheckBox2.Checked;
  15. }
  16. }

将当前页面中DataGrid1显示的数据全部删除

  1. foreach(DataGridItem thisitem in DataGrid1.Items)
  2. {
  3. if(((CheckBox)thisitem.Cells[0].Controls[1]).Checked)
  4. {
  5. string strloginid= DataGrid1.DataKeys[thisitem.ItemIndex].ToString();
  6. Del (strloginid); //删除函数
  7. }
  8. }

40.当文件在不同目录下,需要获取数据库连接字符串(如果连接字符串放在Web.config,然后在Global.asax中初始化) Application_Start中添加以下代码:

  1. Application[&quot;ConnStr&quot;]=this.Context.Request.PhysicalApplicationPath+ConfigurationSettings.
  2. AppSettings[&quot;ConnStr&quot;].ToString();

3 41 变量.ToString() 字符型转换 转为字符串

  1. 12345.ToString(&quot;n&quot;); //生成 12,345.00
  2. 12345.ToString(&quot;C&quot;); //生成 ¥12,345.00
  3. 12345.ToString(&quot;e&quot;); //生成 1.234500e+004
  4. 12345.ToString(&quot;f4&quot;); //生成 12345.0000
  5. 12345.ToString(&quot;x&quot;); //生成 3039 (16进制)
  6. 12345.ToString(&quot;p&quot;); //生成 1,234,500.00%

42、变量.Substring(参数1,参数2); 截取字串的一部分,参数1为左起始位数,参数2为截取几位。 如:string s1 = str.Substring(0,2); 43.在自己的网站上登陆其他网站:(如果你的页面是通过嵌套方式的话,因为一个页面只能有一个FORM,这时可以导向另外一个页面再提交登陆信息)

  1. <SCRIPT language=&quot;javascript&quot;>
  2. <!--
  3. function gook(pws)
  4. {
  5. frm.submit();
  6. }
  7. //-->
  8. </SCRIPT> <body leftMargin=&quot;0&quot; topMargin=&quot;0&quot;  marginwidth=&quot;0&quot; marginheight=&quot;0&quot;>
  9. <form name=&quot;frm&quot; action=&quot; http://www.51aspx.com &quot; method=&quot;post&quot;>
  10. <tr>
  11. <td>
  12. <input id=&quot;f_user&quot; type=&quot;hidden&quot; size=&quot;1&quot; name=&quot;f_user&quot; runat=&quot;server&quot;>
  13. <input id=&quot;f_domain&quot; type=&quot;hidden&quot; size=&quot;1&quot; name=&quot;f_domain&quot; runat=&quot;server&quot;>
  14. <input class=&quot;box&quot; id=&quot;f_pass&quot; type=&quot;hidden&quot; size=&quot;1&quot; name=&quot;pwshow&quot; runat=&quot;server&quot;>
  15. <INPUT id=&quot;lng&quot; type=&quot;hidden&quot; maxLength=&quot;20&quot; size=&quot;1&quot; value=&quot;5&quot; name=&quot;lng&quot;>
  16. <INPUT id=&quot;tem&quot; type=&quot;hidden&quot; size=&quot;1&quot; value=&quot;2&quot; name=&quot;tem&quot;>
  17. </td>
  18. </tr>
  19. </form>

文本框的名称必须是你要登陆的网页上的名称,如果源码不行可以用vsniffer 看看。 下面是获取用户输入的登陆信息的代码:

  1. string name;
  2. name=Request.QueryString[&quot;EmailName&quot;];
  3. try
  4. {
  5. int a=name.IndexOf(&quot;@&quot;,0,name.Length);
  6. f_user.Value=name.Substring(0,a);
  7. f_domain.Value=name.Substring(a+1,name.Length-(a+1));
  8. f_pass.Value=Request.QueryString[&quot;Psw&quot;];
  9. }
  10. catch
  11. {
  12. Script.Alert(&quot;错误的邮箱!&quot;);
  13. Server.Transfer(&quot;index.aspx&quot;);
  14. }

44.datagrid分页中如果删除时出现超出索引

  1. public void jumppage(System.Web.UI.WebControls.DataGrid dg)
  2. {
  3. int int_PageLess; //定义页面跳转的页数
  4. //如果当前页是最后一页
  5. if(dg.CurrentPageIndex == dg.PageCount-1)
  6. {
  7. //如果就只有一页
  8. if(dg.CurrentPageIndex == 0)
  9. {
  10. //删除后页面停在当前页
  11. dg.CurrentPageIndex = dg.PageCount-1;
  12. }
  13. else
  14. {
  15. //如果最后一页只有一条记录
  16. if((dg.Items.Count % dg.PageSize == 1) || dg.PageSize == 1)
  17. {
  18. //把最后一页最后一条记录删除后,页面应跳转到前一页
  19. int_PageLess = 2;
  20. }
  21. else //如果最后一页的记录数大于1,那么在最后一页删除记录后仍然停在当前页
  22. {
  23. int_PageLess = 1;
  24. }
  25. dg.CurrentPageIndex = dg.PageCount - int_PageLess;
  26. }
  27. }
  28. }

45.警告窗口 /**//// <summary> /// 服务器端弹出alert对话框 /// </summary> /// <param name="str_Message">提示信息,例子:"不能为空!"</param> /// <param name="page">Page</param> public void Alert(string str_Message,Page page) { page.RegisterStartupScript("","<script>alert('"+str_Message+"');</script>"); } 36.重载此警告窗口,使某控件获得焦点

  1. /**//// <summary>
  2. /// 服务器端弹出alert对话框,并使控件获得焦点
  3. /// </summary>
  4. /// <param name=&quot;str_Ctl_Name&quot;>获得焦点控件Id值,比如:txt_Name</param>
  5. /// <param name=&quot;str_Message&quot;>提示信息,例子:&quot;请输入您姓名!&quot;</param>
  6. /// <param name=&quot;page&quot;>Page类</param>
  7. public void Alert(string str_Ctl_Name,string str_Message,Page page)
  8. {
  9. page.RegisterStartupScript(&quot;&quot;,&quot;<script>alert('&quot;+str_Message+&quot;');document.forms(0).&quot;+str_Ctl_Name+&quot;.focus(); document.forms(0).&quot;+str_Ctl_Name+&quot;.select();</script>&quot;);
  10. }

47.确认对话框

  1. /**//// <summary>
  2. /// 服务器端弹出confirm对话框
  3. /// </summary>
  4. /// <param name=&quot;str_Message&quot;>提示信息,例子:&quot;您是否确认删除!&quot;</param>
  5. /// <param name=&quot;btn&quot;>隐藏Botton按钮Id值,比如:btn_Flow</param>
  6. /// <param name=&quot;page&quot;>Page类</param>
  7. public void Confirm(string str_Message,string btn,Page page)
  8. {
  9. page.RegisterStartupScript(&quot;&quot;,&quot;<script> if (confirm('&quot;+str_Message+&quot;')==true){document.forms(0).&quot;+btn+&quot;.click();}</script>&quot;);
  10. }

48.重载确认对话框,点击确定触发一个隐藏按钮事件,点击取消触发一个隐藏按钮事件

  1. /**//// <summary>
  2. /// 服务器端弹出confirm对话框,询问用户准备转向那些操作,包括“确定”和“取消”时的操作
  3. /// </summary>
  4. /// <param name=&quot;str_Message&quot;>提示信息,比如:&quot;成功增加数据,单击\&quot;确定\&quot;按钮填写流程,单击\&quot;取消\&quot;修改数据&quot;</param>
  5. /// <param name=&quot;btn_Redirect_Flow&quot;>&quot;确定&quot;按钮id值</param>
  6. /// <param name=&quot;btn_Redirect_Self&quot;>&quot;取消&quot;按钮id值</param>
  7. /// <param name=&quot;page&quot;>Page类</param>
  8. public void Confirm(string str_Message,string btn_Redirect_Flow,string btn_Redirect_Self,Page page)
  9. {
  10. page.RegisterStartupScript(&quot;&quot;,&quot;<script> if (confirm('&quot;+str_Message+&quot;')==true){document.forms(0).&quot;+btn_Redirect_Flow+&quot;.click();}else{document.forms(0).&quot;+btn_Redirect_Self+&quot;.click();}</script>&quot;);
  11. }

49.获得焦点

  1. /**//// <summary>
  2. /// 使控件获得焦点
  3. /// </summary>
  4. /// <param name=&quot;str_Ctl_Name&quot;>获得焦点控件Id值,比如:txt_Name</param>
  5. /// <param name=&quot;page&quot;>Page类</param>
  6. public void GetFocus(string str_Ctl_Name,Page page)
  7. {
  8. page.RegisterStartupScript(&quot;&quot;,&quot;<script>document.forms(0).&quot;+str_Ctl_Name+&quot;.focus(); document.forms(0).&quot;+str_Ctl_Name+&quot;.select();</script>&quot;);
  9. }



原标题:Asp.net常用的51个代码

关键词:ASP.NET

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

美国fba海运的费用是多少:https://www.goluckyvip.com/tag/37994.html
美国fba海运的价格:https://www.goluckyvip.com/tag/37995.html
美国fba海运多少钱:https://www.goluckyvip.com/tag/37996.html
美国fba海运费:https://www.goluckyvip.com/tag/37997.html
美国fba海运费用:https://www.goluckyvip.com/tag/37998.html
美国fba海运费用是多少:https://www.goluckyvip.com/tag/37999.html
TikTok Shop美区,Q2特惠福利,心动不如行动 :https://www.goluckyvip.com/news/217212.html
TikTok Shop美区,Q2特惠福利,心动不如行动 :https://www.xlkjsw.com/news/90170.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流