Hopes

          Start Here..

           

          Asp.net常用的51個代碼(非常實用)

          Asp.net常用的51個代碼(非常實用) [復制鏈接]

          51aspx


          51Aspx


          組別
          超級管理員
          生日
          帖子
          2197
          論壇積分
          4779 分
          性別

          注冊時間
          2007-05-17
          1#
          字體大小:


          發表于 2007-06-10 00:50 |只看樓主
          常用代碼 asp.net
          1.//彈出對話框.點擊轉向指定頁面
          Response.Write(&quot;<script>window.alert('該會員沒有提交申請,請重新提交!')</script>&quot;);
          Response.Write(&quot;<script>window.location ='http://www.51aspx.com/bizpulic/upmeb.aspx'</script>&quot;);
          復制代碼
          2.//彈出對話框
          Response.Write(&quot;<script language='javascript'>alert('產品添加成功!')</script >&quot;);
          復制代碼
          3.//刪除文件
          string filename =&quot;20059595157517.jpg&quot;;
          pub.util.DeleteFile(HttpContext.Current.Server.MapPath(&quot;../file/&quot;)+filename);
          復制代碼
          4.//綁定下拉列表框datalist
          System.Data.DataView dv=conn.Exec_ex(&quot;select -1 as code,'請選擇經營模式' as content from dealin union select code,content from dealin&quot;);
          this.dealincode.DataSource=dv;
          this.dealincode.DataTextField=&quot;content&quot;;
          this.dealincode.DataValueField=&quot;code&quot;;
          this.dealincode.DataBind();
          this.dealincode.Items.FindByValue(dv[0][&quot;dealincode&quot;].ToString()).Selected=true;
          復制代碼
          5.//時間去秒顯示
          <%# System.DateTime.Parse(DataBinder.Eval(Container.DataItem,&quot;begtime&quot;).ToString()).ToShortDateString()%>
          復制代碼
          6.//標題帶鏈接
          <%# &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.//修改轉向
          <%# &quot;<A href=\&quot;editpushpro.aspx?id=&quot;+DataBinder.Eval(Container.DataItem,&quot;code&quot;)+&quot;\&quot;>&quot;+&quot;修改&quot;+&quot;</A>&quot;%>
          復制代碼
          8.//彈出確定按鈕
          <%# &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表示小數點后剩兩位
          <%# DataBinder.Eval(Container, &quot;DataItem.PriceMoney&quot;,&quot;{0:F2}&quot;) %>
          復制代碼
          10.//提取動態網頁內容
          Uri uri = new Uri(&quot;http://www.51aspx.com/&quot;);
          WebRequest req = WebRequest.Create(uri);
          WebResponse resp = req.GetResponse();
          Stream str = resp.GetResponseStream();
          StreamReader sr = new StreamReader(str,System.Text.Encoding.Default);
          string t = sr.ReadToEnd();
          this.Response.Write(t.ToString());
          復制代碼
          11.//獲取" . "后面的字符
          i.ToString().Trim().Substring(i.ToString().Trim().LastIndexOf(&quot;.&quot;)+1).ToLower().Trim()
          復制代碼
          12. 打開新的窗口并傳送參數:   傳送參數:
          response.write(&quot;<script>window.open(’*.aspx?id=&quot;+this.DropDownList1.SelectIndex+&quot;&amp;id1=&quot;+...+&quot;’)</script>&quot;)
          復制代碼
          接收參數:
          string a = Request.QueryString(&quot;id&quot;);
          string b = Request.QueryString(&quot;id1&quot;);
          復制代碼
          12.為按鈕添加對話框
          Button1.Attributes.Add(&quot;onclick&quot;,&quot;return confirm(’確認?’)&quot;);
          button.attributes.add(&quot;onclick&quot;,&quot;if(confirm(’are you sure...?’)){return true;}else{return false;}&quot;)
          復制代碼
          13.刪除表格選定記錄
          int intEmpID = (int)MyDataGrid.DataKeys[e.Item.ItemIndex];
          string deleteCmd = &quot;Delete from Employee where emp_id = &quot; + intEmpID.ToString()
          復制代碼
          14.刪除表格記錄警告
          private void DataGrid_ItemCreated(Object sender,DataGridItemEventArgs e)
          {
          switch(e.Item.ItemType)
          {
          case ListItemType.Item :
          case ListItemType.AlternatingItem :
          case ListItemType.EditItem:
          TableCell myTableCell;
          myTableCell = e.Item.Cells[14];
          LinkButton myDeleteButton ;
          myDeleteButton = (LinkButton)myTableCell.Controls[0];
          myDeleteButton.Attributes.Add(&quot;onclick&quot;,&quot;return confirm(’您是否確定要刪除這條信息’);&quot;);
          break;
          default:
          break;
          }
          }
          復制代碼
          15.點擊表格行鏈接另一頁
          private void grdCustomer_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
          {
          //點擊表格打開
          if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
          e.Item.Attributes.Add(&quot;onclick&quot;,&quot;window.open(’Default.aspx?id=&quot; + e.Item.Cells[0].Text + &quot;’);&quot;);
          }
          復制代碼
          雙擊表格連接到另一頁   在itemDataBind事件中
          if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
          {
          string orderItemID =e.item.cells[1].Text;
          e.item.Attributes.Add(&quot;ondblclick&quot;, &quot;location.href=’../ShippedGrid.aspx?id=&quot; + orderItemID + &quot;’&quot;);
          }
          復制代碼
          雙擊表格打開新一頁
          if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
          {
          string orderItemID =e.item.cells[1].Text;
          e.item.Attributes.Add(&quot;ondblclick&quot;, &quot;open(’../ShippedGrid.aspx?id=&quot; + orderItemID + &quot;’)&quot;);
          }
          復制代碼
          16.表格超連接列傳遞參數
          <asp:HyperLinkColumn Target=&quot;_blank&quot; headertext=&quot;ID號&quot; DataTextField=&quot;id&quot; NavigateUrl=&quot;aaa.aspx?id=’
          <%# DataBinder.Eval(Container.DataItem, &quot;數據字段1&quot;)%>’ &amp; name=’<%# DataBinder.Eval(Container.DataItem, &quot;數據字段2&quot;)%>’ />
          復制代碼
          17.表格點擊改變顏色
          if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem)
          {
          e.Item.Attributes.Add(&quot;onclick&quot;,&quot;this.style.backgroundColor=’#99cc00’;
          this.style.color=’buttontext’;this.style.cursor=’default’;&quot;);
          }
          復制代碼
          寫在DataGrid的_ItemDataBound里
          if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem)
          {
          e.Item.Attributes.Add(&quot;onmouseover&quot;,&quot;this.style.backgroundColor=’#99cc00’;
          this.style.color=’buttontext’;this.style.cursor=’default’;&quot;);
          e.Item.Attributes.Add(&quot;onmouseout&quot;,&quot;this.style.backgroundColor=’’;this.style.color=’’;&quot;);
          }
          復制代碼
          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
          // in global.asax
          protected void Application_Error(Object sender, EventArgs e) {
          if (Server.GetLastError() is HttpUnhandledException)
          Server.Transfer(&quot;MyErrorPage.aspx&quot;);
          復制代碼
          //其余的非HttpUnhandledException異常交給ASP.NET自己處理就okay了 :) }   Redirect會導致post-back的產生從而丟失了錯誤信息,所以頁面導向應該直接在服務器端執行,這樣就可以在錯誤處理頁面得到出錯信息并進行相應的處理 20.清空Cookie
          Cookie.Expires=[DateTime];
          Response.Cookies(&quot;UserName&quot;).Expires = 0
          復制代碼
          21.自定義異常處理
          //自定義異常處理類
          using System;
          using System.Diagnostics;
          namespace MyAppException
          {
          /// <summary>
          /// 從系統異常類ApplicationException繼承的應用程序異常處理類。
          /// 自動將異常內容記錄到Windows NT/2000的應用程序日志
          /// </summary>
          public class AppException:System.ApplicationException
          {
          public AppException()
          {
          if (ApplicationConfiguration.EventLogEnabled)LogEvent(&quot;出現一個未知錯誤。&quot;);
          }
          public AppException(string message)
          {
          LogEvent(message);
          }
          public AppException(string message,Exception innerException)
          {
          LogEvent(message);
          if (innerException != null)
          {
          LogEvent(innerException.Message);
          }
          }
          //日志記錄類
          using System;
          using System.Configuration;
          using System.Diagnostics;
          using System.IO;
          using System.Text;
          using System.Threading;
          namespace MyEventLog
          {
          /// <summary>
          /// 事件日志記錄類,提供事件日志記錄支持
          /// <remarks>
          /// 定義了4個日志記錄方法 (error, warning, info, trace)
          /// </remarks>
          /// </summary>
          public class ApplicationLog
          {
          /// <summary>
          /// 將錯誤信息記錄到Win2000/NT事件日志中
          /// <param name=&quot;message&quot;>需要記錄的文本信息</param>
          /// </summary>
          public static void WriteError(String message)
          {
          WriteLog(TraceLevel.Error, message);
          }
          /// <summary>
          /// 將警告信息記錄到Win2000/NT事件日志中
          /// <param name=&quot;message&quot;>需要記錄的文本信息</param>
          /// </summary>
          public static void WriteWarning(String message)
          {
          WriteLog(TraceLevel.Warning, message);  
          }
          /// <summary>
          /// 將提示信息記錄到Win2000/NT事件日志中
          /// <param name=&quot;message&quot;>需要記錄的文本信息</param>
          /// </summary>
          public static void WriteInfo(String message)
          {
          WriteLog(TraceLevel.Info, message);
          }
          /// <summary>
          /// 將跟蹤信息記錄到Win2000/NT事件日志中
          /// <param name=&quot;message&quot;>需要記錄的文本信息</param>
          /// </summary>
          public static void WriteTrace(String message)
          {
          WriteLog(TraceLevel.Verbose, message);
          }
          /// <summary>
          /// 格式化記錄到事件日志的文本信息格式
          /// <param name=&quot;ex&quot;>需要格式化的異常對象</param>
          /// <param name=&quot;catchInfo&quot;>異常信息標題字符串.</param>
          /// <retvalue>
          /// <para>格式后的異常信息字符串,包括異常內容和跟蹤堆棧.</para>
          /// </retvalue>
          /// </summary>
          public static String FormatException(Exception ex, String catchInfo)
          {
          StringBuilder strBuilder = new StringBuilder();
          if (catchInfo != String.Empty)
          {
          strBuilder.Append(catchInfo).Append(&quot;\r\n&quot;);
          }
          strBuilder.Append(ex.Message).Append(&quot;\r\n&quot;).Append(ex.StackTrace);
          return strBuilder.ToString();
          }
          /// <summary>
          /// 實際事件日志寫入方法
          /// <param name=&quot;level&quot;>要記錄信息的級別(error,warning,info,trace).</param>
          /// <param name=&quot;messageText&quot;>要記錄的文本.</param>
          /// </summary>
          private static void WriteLog(TraceLevel level, String messageText)
          {
          try
          {
          EventLogEntryType LogEntryType;
          switch (level)
          {
          case TraceLevel.Error:
          LogEntryType = EventLogEntryType.Error;
          break;
          case TraceLevel.Warning:
          LogEntryType = EventLogEntryType.Warning;
          break;
          case TraceLevel.Info:
          LogEntryType = EventLogEntryType.Information;
          break;
          case TraceLevel.Verbose:
          LogEntryType = EventLogEntryType.SuccessAudit;
          break;
          default:
          LogEntryType = EventLogEntryType.SuccessAudit;
          break;
          }
          EventLog eventLog = new EventLog(&quot;Application&quot;, ApplicationConfiguration.EventLogMachineName, ApplicationConfiguration.EventLogSourceName );
          //寫入事件日志
          eventLog.WriteEntry(messageText, LogEntryType);
          }
          catch {} //忽略任何異常
          }
          } //class ApplicationLog
          }
          復制代碼
          22.Panel 橫向滾動,縱向自動擴展
          <asp:panel style=&quot;overflow-x:scroll;overflow-y:auto;&quot;></asp:panel>
          復制代碼
          23.回車轉換成Tab (1)
          <script language=&quot;javascript&quot; for=&quot;document&quot; event=&quot;onkeydown&quot;>
          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’);
          event.keyCode=9;
          </script>
          復制代碼
          (2) //當在有keydown事件的控件上敲回車時,變為tab
          public void Tab(System.Web .UI.WebControls .WebControl webcontrol)
          {
          webcontrol.Attributes .Add (&quot;onkeydown&quot;, &quot;if(event.keyCode==13) event.keyCode=9&quot;);
          }
          24.DataGrid超級連接列
          DataNavigateUrlField=&quot;字段名&quot; DataNavigateUrlFormatString=&quot;http://xx/inc/delete.aspx?ID={0}&quot;
          復制代碼
          25.DataGrid行隨鼠標變色
          private void DGzf_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
          {
          if (e.Item.ItemType!=ListItemType.Header)
          {
          e.Item.Attributes.Add( &quot;onmouseout&quot;,&quot;this.style.backgroundColor=\&quot;&quot;+e.Item.Style[&quot;BACKGROUND-COLOR&quot;]+&quot;\&quot;&quot;);
          e.Item.Attributes.Add( &quot;onmouseover&quot;,&quot;this.style.backgroundColor=\&quot;&quot;+ &quot;#EFF3F7&quot;+&quot;\&quot;&quot;);
          }
          }
          復制代碼
          26.模板列
          <ASP:TEMPLATECOLUMN visible=&quot;False&quot; sortexpression=&quot;demo&quot; headertext=&quot;ID&quot;>
          <ITEMTEMPLATE>
          <ASP LABEL text=’<%# DataBinder.Eval(Container.DataItem, &quot;ArticleID&quot;)%>’ runat=&quot;server&quot; width=&quot;80%&quot; id=&quot;lblColumn&quot; />
          </ITEMTEMPLATE>
          </ASP:TEMPLATECOLUMN>
          <ASP:TEMPLATECOLUMN headertext=&quot;選中&quot;>
          <HEADERSTYLE wrap=&quot;False&quot; horiz></HEADERSTYLE>
          <ITEMTEMPLATE>
          <ASP:CHECKBOX id=&quot;chkExport&quot; runat=&quot;server&quot; />
          </ITEMTEMPLATE>
          <EDITITEMTEMPLATE>
          <ASP:CHECKBOX id=&quot;chkExportON&quot; runat=&quot;server&quot; enabled=&quot;true&quot; />
          </EDITITEMTEMPLATE>
          </ASP:TEMPLATECOLUMN>
          復制代碼
          后臺代碼
          protected void CheckAll_CheckedChanged(object sender, System.EventArgs e)
          {
          //改變列的選定,實現全選或全不選。
          CheckBox chkExport ;
          if( CheckAll.Checked)
          {
          foreach(DataGridItem oDataGridItem in MyDataGrid.Items)
          {
          chkExport = (CheckBox)oDataGridItem.FindControl(&quot;chkExport&quot;);
          chkExport.Checked = true;
          }
          }
          else
          {
          foreach(DataGridItem oDataGridItem in MyDataGrid.Items)
          {
          chkExport = (CheckBox)oDataGridItem.FindControl(&quot;chkExport&quot;);
          chkExport.Checked = false;
          }
          }
          }
          復制代碼
          27.數字格式化
          【<%#Container.DataItem(&quot;price&quot;)%>的結果是500.0000,怎樣格式化為500.00?】
          <%#Container.DataItem(&quot;price&quot;,&quot;{0:¥#,##0.00}&quot;)%>
          int i=123456;
          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.xml文件的菜單項中加入URLTarget="_blank",如:
          <?xml version=&quot;1.0&quot; encoding=&quot;GB2312&quot;?>
          <MenuData ImagesBaseURL=&quot;images/&quot;>
          <MenuGroup>
          <MenuItem Label=&quot;內參信息&quot; URL=&quot;Infomation.aspx&quot; >
          <MenuGroup ID=&quot;BBC&quot;>
          <MenuItem Label=&quot;公告信息&quot; URL=&quot;Infomation.aspx&quot; URLTarget=&quot;_blank&quot; LeftIcon=&quot;file.gif&quot;/>
          <MenuItem Label=&quot;編制信息簡報&quot; URL=&quot;NewInfo.aspx&quot; LeftIcon=&quot;file.gif&quot; />
          復制代碼
          最好將你的aspnetmenu升級到1.2版 31.讀取DataGrid控件TextBox值
          foreach(DataGrid dgi in yourDataGrid.Items)
          {
          TextBox tb = (TextBox)dgi.FindControl(&quot;yourTextBoxId&quot;);
          tb.Text....
          }
          復制代碼
          33.在DataGrid中有3個模板列包含Textbox分別為 DG_ShuLiang (數量) DG_DanJian(單價) DG_JinE(金額)分別在5.6.7列,要求在錄入數量及單價的時候自動算出金額即:數量*單價=金額還要求錄入時限制為 數值型.我如何用客戶端腳本實現這個功能?
          <asp:TemplateColumn HeaderText=&quot;數量&quot;>
          <ItemTemplate>
          <asp:TextBox id=&quot;ShuLiang&quot; runat=’server’ Text=’<%# DataBinder.Eval(Container.DataItem,&quot;DG_ShuLiang&quot;)%>’

          />
          <asp:RegularExpressionValidator id=&quot;revS&quot; runat=&quot;server&quot; C ErrorMessage=&quot;must be integer&quot; Validati />
          </ItemTemplate>
          </asp:TemplateColumn>
          <asp:TemplateColumn HeaderText=&quot;單價&quot;>
          <ItemTemplate>
          <asp:TextBox id=&quot;DanJian&quot; runat=’server’ Text=’<%# DataBinder.Eval(Container.DataItem,&quot;DG_DanJian&quot;)%>’

          />
          <asp:RegularExpressionValidator id=&quot;revS2&quot; runat=&quot;server&quot; C ErrorMessage=&quot;must be numeric&quot; Validati />
          </ItemTemplate>
          </asp:TemplateColumn>
          <asp:TemplateColumn HeaderText=&quot;金額&quot;>
          <ItemTemplate>
          <asp:TextBox id=&quot;JinE&quot; runat=’server’ Text=’<%# DataBinder.Eval(Container.DataItem,&quot;DG_JinE&quot;)%>’ />
          </ItemTemplate>
          </asp:TemplateColumn><script language=&quot;javascript&quot;>
          function DoCal()
          {
          var e = event.srcElement;
          var row = e.parentNode.parentNode;
          var txts = row.all.tags(&quot;INPUT&quot;);
          if (!txts.length || txts.length < 3)
          return;
          var q = txts[txts.length-3].value;
          var p = txts[txts.length-2].value;
          if (isNaN(q) || isNaN(p))
          return;
          q = parseInt(q);
          p = parseFloat(p);
          txts[txts.length-1].value = (q * p).toFixed(2);
          }
          </script>
          復制代碼
          34.datagrid選定比較底下的行時,為什么總是刷新一下,然后就滾動到了最上面,剛才選定的行因屏幕的關系就看不到了。 page_load page.smartNavigation=true 35.在Datagrid中修改數據,當點擊編輯鍵時,數據出現在文本框中,怎么控制文本框的大小 ?
          private void DataGrid1_ItemDataBound(obj sender,DataGridItemEventArgs e)
          {
          for(int i=0;i<e.Item.Cells.Count-1;i++)
          if(e.Item.ItemType==ListItemType.EditType)
          {
          e.Item.Cells.Attributes.Add(&quot;Width&quot;, &quot;80px&quot;)
          }
          }
          復制代碼
          36.對話框
          private static string ScriptBegin = &quot;<script language=\&quot;JavaScript\&quot;>&quot;;
          private static string ScriptEnd = &quot;</script>&quot;;
          public static void ConfirmMessageBox(string PageTarget,string Content)
          {
          string C+Content+&quot;’);&quot;+&quot;if(retValue){window.location=’&quot;+PageTarget+&quot;’;}&quot;;
          ConfirmContent=ScriptBegin + ConfirmContent + ScriptEnd;
          Page ParameterPage = (Page)System.Web.HttpContext.Current.Handler;
          ParameterPage.RegisterStartupScript(&quot;confirm&quot;,ConfirmContent);
          //Response.Write
          復制代碼
          (strScript); } 37. 將時間格式化:string aa=DateTime.Now.ToString("yyyy年MM月dd日");   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.自定義分頁代碼:   先定義變量 :
          public static int pageCount; //總頁面數
          public static int curPageIndex=1; //當前頁面
          下一頁:
          if(DataGrid1.CurrentPageIndex < (DataGrid1.PageCount - 1))
          {
          DataGrid1.CurrentPageIndex += 1;
          curPageIndex+=1;
          }
          bind(); // DataGrid1數據綁定函數
          上一頁:
          if(DataGrid1.CurrentPageIndex >0)
          {
          DataGrid1.CurrentPageIndex += 1;
          curPageIndex-=1;
          }
          bind(); // DataGrid1數據綁定函數
          直接頁面跳轉:
          int a=int.Parse(JumpPage.Value.Trim());//JumpPage.Value.Trim()為跳轉值
          if(a<DataGrid1.PageCount)
          {
          this.DataGrid1.CurrentPageIndex=a;
          }
          bind();
          復制代碼
          39.DataGrid使用:   添加刪除確認:
          private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
          {
          foreach(DataGridItem di in this.DataGrid1.Items)
          {
          if(di.ItemType==ListItemType.Item||di.ItemType==ListItemType.AlternatingItem)
          {
          ((LinkButton)di.Cells[8].Controls[0]).Attributes.Add(&quot;onclick&quot;,&quot;return confirm(’確認刪除此項嗎?’);&quot;);
          }
          }
          }
          復制代碼
          樣式交替:
          ListItemType itemType = e.Item.ItemType;
          if (itemType == ListItemType.Item )
          {
          e.Item.Attributes[&quot;onmouseout&quot;] = &quot;javascript:this.style.backgroundColor=’#FFFFFF’;&quot;;
          e.Item.Attributes[&quot;onmouseover&quot;] = &quot;javascript:this.style.backgroundColor=’#d9ece1’;cursor=’hand’;&quot; ;
          }
          else if( itemType == ListItemType.AlternatingItem)
          {
          e.Item.Attributes[&quot;onmouseout&quot;] = &quot;javascript:this.style.backgroundColor=’#a0d7c4’;&quot;;
          e.Item.Attributes[&quot;onmouseover&quot;] = &quot;javascript:this.style.backgroundColor=’#d9ece1’;cursor=’hand’;&quot; ;
          }
          復制代碼
          添加一個編號列:
          DataTable dt= c.ExecuteRtnTableForAccess(sqltxt); //執行sql返回的DataTable
          DataColumn dc=dt.Columns.Add(&quot;number&quot;,System.Type.GetType(&quot;System.String&quot;));
          for(int i=0;i<dt.Rows.Count;i++)
          {
          dt.Rows[&quot;number&quot;]=(i+1).ToString();
          }
          DataGrid1.DataSource=dt;
          DataGrid1.DataBind();
          DataGrid1中添加一個CheckBox,頁面中添加一個全選框
          private void CheckBox2_CheckedChanged(object sender, System.EventArgs e)
          {
          foreach(DataGridItem thisitem in DataGrid1.Items)
          {
          ((CheckBox)thisitem.Cells[0].Controls[1]).Checked=CheckBox2.Checked;
          }
          }
          復制代碼
          將當前頁面中DataGrid1顯示的數據全部刪除
          foreach(DataGridItem thisitem in DataGrid1.Items)
          {
          if(((CheckBox)thisitem.Cells[0].Controls[1]).Checked)
          {
          string strloginid= DataGrid1.DataKeys[thisitem.ItemIndex].ToString();
          Del (strloginid); //刪除函數
          }
          }
          復制代碼
          40.當文件在不同目錄下,需要獲取數據庫連接字符串(如果連接字符串放在Web.config,然后在Global.asax中初始化)   在Application_Start中添加以下代碼:
          Application[&quot;ConnStr&quot;]=this.Context.Request.PhysicalApplicationPath+ConfigurationSettings.
          AppSettings[&quot;ConnStr&quot;].ToString();
          復制代碼
          3 41. 變量.ToString()   字符型轉換 轉為字符串
          12345.ToString(&quot;n&quot;); //生成 12,345.00
          12345.ToString(&quot;C&quot;); //生成 ¥12,345.00
          12345.ToString(&quot;e&quot;); //生成 1.234500e+004
          12345.ToString(&quot;f4&quot;); //生成 12345.0000
          12345.ToString(&quot;x&quot;); //生成 3039 (16進制)
          12345.ToString(&quot;p&quot;); //生成 1,234,500.00%
          復制代碼
          42、變量.Substring(參數1,參數2);   截取字串的一部分,參數1為左起始位數,參數2為截取幾位。 如:string s1 = str.Substring(0,2); 43.在自己的網站上登陸其他網站:(如果你的頁面是通過嵌套方式的話,因為一個頁面只能有一個FORM,這時可以導向另外一個頁面再提交登陸信息)
          <SCRIPT language=&quot;javascript&quot;>
          <!--
          function gook(pws)
          {
          frm.submit();
          }
          //-->
          </SCRIPT> <body leftMargin=&quot;0&quot; topMargin=&quot;0&quot; marginwidth=&quot;0&quot; marginheight=&quot;0&quot;>
          <form name=&quot;frm&quot; action=&quot; http://www.51aspx.com &quot; method=&quot;post&quot;>
          <tr>
          <td>
          <input id=&quot;f_user&quot; type=&quot;hidden&quot; size=&quot;1&quot; name=&quot;f_user&quot; runat=&quot;server&quot;>
          <input id=&quot;f_domain&quot; type=&quot;hidden&quot; size=&quot;1&quot; name=&quot;f_domain&quot; runat=&quot;server&quot;>
          <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;>
          <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;>
          <INPUT id=&quot;tem&quot; type=&quot;hidden&quot; size=&quot;1&quot; value=&quot;2&quot; name=&quot;tem&quot;>
          </td>
          </tr>
          </form>
          復制代碼
          文本框的名稱必須是你要登陸的網頁上的名稱,如果源碼不行可以用vsniffer 看看。   下面是獲取用戶輸入的登陸信息的代碼:
          string name;
          name=Request.QueryString[&quot;EmailName&quot;];
          try
          {
          int a=name.IndexOf(&quot;@&quot;,0,name.Length);
          f_user.Value=name.Substring(0,a);
          f_domain.Value=name.Substring(a+1,name.Length-(a+1));
          f_pass.Value=Request.QueryString[&quot;Psw&quot;];
          }
          catch
          {
          Script.Alert(&quot;錯誤的郵箱!&quot;);
          Server.Transfer(&quot;index.aspx&quot;);
          }
          復制代碼
          44.datagrid分頁中如果刪除時出現超出索引
          public void jumppage(System.Web.UI.WebControls.DataGrid dg)
          {
          int int_PageLess; //定義頁面跳轉的頁數
          //如果當前頁是最后一頁
          if(dg.CurrentPageIndex == dg.PageCount-1)
          {
          //如果就只有一頁
          if(dg.CurrentPageIndex == 0)
          {
          //刪除后頁面停在當前頁
          dg.CurrentPageIndex = dg.PageCount-1;
          }
          else
          {
          //如果最后一頁只有一條記錄
          if((dg.Items.Count % dg.PageSize == 1) || dg.PageSize == 1)
          {
          //把最后一頁最后一條記錄刪除后,頁面應跳轉到前一頁
          int_PageLess = 2;
          }
          else //如果最后一頁的記錄數大于1,那么在最后一頁刪除記錄后仍然停在當前頁
          {
          int_PageLess = 1;
          }
          dg.CurrentPageIndex = dg.PageCount - int_PageLess;
          }
          }
          }
          復制代碼
          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.重載此警告窗口,使某控件獲得焦點
          /**//// <summary>
          /// 服務器端彈出alert對話框,并使控件獲得焦點
          /// </summary>
          /// <param name=&quot;str_Ctl_Name&quot;>獲得焦點控件Id值,比如:txt_Name</param>
          /// <param name=&quot;str_Message&quot;>提示信息,例子:&quot;請輸入您姓名!&quot;</param>
          /// <param name=&quot;page&quot;>Page類</param>
          public void Alert(string str_Ctl_Name,string str_Message,Page page)
          {
          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;);
          }
          復制代碼
          47.確認對話框
          /**//// <summary>
          /// 服務器端彈出confirm對話框
          /// </summary>
          /// <param name=&quot;str_Message&quot;>提示信息,例子:&quot;您是否確認刪除!&quot;</param>
          /// <param name=&quot;btn&quot;>隱藏Botton按鈕Id值,比如:btn_Flow</param>
          /// <param name=&quot;page&quot;>Page類</param>
          public void Confirm(string str_Message,string btn,Page page)
          {
          page.RegisterStartupScript(&quot;&quot;,&quot;<script> if (confirm('&quot;+str_Message+&quot;')==true){document.forms(0).&quot;+btn+&quot;.click();}</script>&quot;);
          }
          復制代碼
          48.重載確認對話框,點擊確定觸發一個隱藏按鈕事件,點擊取消觸發一個隱藏按鈕事件
          /**//// <summary>
          /// 服務器端彈出confirm對話框,詢問用戶準備轉向那些操作,包括“確定”和“取消”時的操作
          /// </summary>
          /// <param name=&quot;str_Message&quot;>提示信息,比如:&quot;成功增加數據,單擊\&quot;確定\&quot;按鈕填寫流程,單擊\&quot;取消\&quot;修改數據&quot;</param>
          /// <param name=&quot;btn_Redirect_Flow&quot;>&quot;確定&quot;按鈕id值</param>
          /// <param name=&quot;btn_Redirect_Self&quot;>&quot;取消&quot;按鈕id值</param>
          /// <param name=&quot;page&quot;>Page類</param>
          public void Confirm(string str_Message,string btn_Redirect_Flow,string btn_Redirect_Self,Page page)
          {
          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;);
          }
          復制代碼
          49.獲得焦點
          /**//// <summary>
          /// 使控件獲得焦點
          /// </summary>
          /// <param name=&quot;str_Ctl_Name&quot;>獲得焦點控件Id值,比如:txt_Name</param>
          /// <param name=&quot;page&quot;>Page類</param>
          public void GetFocus(string str_Ctl_Name,Page page)
          {
          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;);
          }
          復制代碼
          50.子窗體返回主窗體 /
          **////<summary>
          ///名稱:redirect
          ///功能:子窗體返回主窗體
          ///參數:url
          ///返回值:空
          ///</summary>
          public void redirect(string url,Page page)
          {
          if ( Session[&quot;IfDefault&quot;]!=(object)&quot;Default&quot;)
          {
          page.RegisterStartupScript(&quot;&quot;,&quot;<script>window.top.document.location.href='&quot;+url+&quot;';</script>&quot;);
          }
          }
          復制代碼
          51.判斷是否為數字
          /**//// <summary>
          /// 名稱:IsNumberic
          /// 功能:判斷輸入的是否是數字
          /// 參數:string oText:源文本
          /// 返回值: bool true:是 false:否
          /// </summary>
          public bool IsNumberic(string oText)
          {
          try
          {
          int var1=Convert.ToInt32 (oText);
          return true;
          }
          catch
          {
          return false;
          }
          }
          復制代碼
          獲得字符串實際長度(包括中文字符)
          //獲得字符串oString的實際長度
          public int StringLength(string oString)
          {
          byte[] strArray=System.Text .Encoding.Default .GetBytes (oString);
          int res=strArray.Length ;
          return res;
          }
          復制代碼

          posted on 2012-10-28 12:06 ** 閱讀(118) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           

          導航

          統計

          公告

          你好!

          常用鏈接

          留言簿(2)

          隨筆檔案

          文章分類

          文章檔案

          新聞檔案

          相冊

          收藏夾

          C#學習

          友情鏈接

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 资溪县| 平凉市| 海丰县| 达日县| 六安市| 乌审旗| 沿河| 砀山县| 镇雄县| 宣化县| 济宁市| 高青县| 蒙城县| 庄河市| 平顺县| 岚皋县| 湄潭县| 甘洛县| 安乡县| 固镇县| 繁峙县| 景洪市| 苍梧县| 明水县| 周至县| 宁海县| 西安市| 无锡市| 阳江市| 伽师县| 定南县| 和平县| 银川市| 台州市| 崇阳县| 三门峡市| 视频| 高雄市| 保定市| 延边| 宁武县|