熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

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

2022-06-13   來源: .NET編程 

  彈出對話框點擊轉向指定頁面

  Code:

  ResponseWrite(<script>windowalert(該會員沒有提交申請請重新提交!)</script>);

  ResponseWrite(<script>windowlocation =</script>);

  彈出對話框

  Code:

  ResponseWrite(<script language=javascript>alert(產品添加成功!)</script >);

  刪除文件

  Code:

  string filename =jpg;

  pubutilDeleteFile(HttpContextCurrentServerMapPath(/file/)+filename);

  綁定下拉列表框datalist

  Code:

  SystemDataDataView dv=connExec_ex(select as code請選擇經營模式 as content from dealin union select codecontent from dealin);

  thisdealincodeDataSource=dv;

  thisdealincodeDataTextField=content;

  thisdealincodeDataValueField=code;

  thisdealincodeDataBind();

  thisdealincodeItemsFindByValue(dv[][dealincode]ToString())Selected=true;

  時間去秒顯示

  Code:

  <%# SystemDateTimeParse(DataBinderEval(ContainerDataItembegtime)ToString())ToShortDateString()%>

  標題帶鏈接

  Code:

  <%# <a class=\c\ target=\_blank\ href=\_+DataBinderEval(ContainerDataItemprocode)+l\>+ DataBinderEval(ContainerDataItemproname)+</a>%>

  修改轉向

  Code:

  <%# <A href=\editpushproaspx?id=+DataBinderEval(ContainerDataItemcode)+\>+修改+</A>%>

  彈出確定按鈕

  Code:

  <%# <A id=\btnDelete\ onclick=\return confirm(你是否確定刪除這條記錄嗎?);\ href=\pushproductaspx?dl=+DataBinderEval(ContainerDataItemcode)+\>+刪除+</A>%>

  輸出數據格式化 {:F} 是格式 F表示小數點後剩兩位

  Code:

  <%# DataBinderEval(Container DataItemPriceMoney{:F}) %>

  提取動態網頁內容

  Code:

  Uri uri = new Uri();

  WebRequest req = WebRequestCreate(uri);

  WebResponse resp = reqGetResponse();

  Stream str = respGetResponseStream();

  StreamReader sr = new StreamReader(strSystemTextEncodingDefault);

  string t = srReadToEnd();

  thisResponseWrite(tToString());

  獲取 後面的字符

  Code:

  iToString()Trim()Substring(iToString()Trim()LastIndexOf()+)ToLower()Trim()

   打開新的窗口並傳送參數

  傳送參數

  Code:

  responsewrite(<script>windowopen(*aspx?id=+thisDropDownListSelectIndex+&id=++)</script>)

  接收參數

  Code:

  string a = RequestQueryString(id);

  string b = RequestQueryString(id);

  為按鈕添加對話框

  Code:

  ButtonAttributesAdd(onclickreturn confirm(確認?));

  buttonattributesadd(onclickif(confirm(are you sure?)){return true;}else{return false;})

  刪除表格選定記錄

  Code:

  int intEmpID = (int)MyDataGridDataKeys[eItemItemIndex];

  string deleteCmd = Delete from Employee where emp_id = + intEmpIDToString()

  刪除表格記錄警告

  Code:

  private void DataGrid_ItemCreated(Object senderDataGridItemEventArgs e)

  {

  switch(eItemItemType)

  {

  case ListItemTypeItem :

  case ListItemTypeAlternatingItem :

  case ListItemTypeEditItem:

  TableCell myTableCell;

  myTableCell = eItemCells[];

  LinkButton myDeleteButton ;

  myDeleteButton = (LinkButton)myTableCellControls[];

  myDeleteButtonAttributesAdd(onclickreturn confirm(您是否確定要刪除這條信息););

  break;

  default:

  break;

  }

  }

  點擊表格行鏈接另一頁

  Code:

  private void grdCustomer_ItemDataBound(object sender SystemWebUIWebControlsDataGridItemEventArgs e)

  {

  //點擊表格打開

  if (eItemItemType == ListItemTypeItem || eItemItemType == ListItemTypeAlternatingItem)

  eItemAttributesAdd(onclickwindowopen(Defaultaspx?id= + eItemCells[]Text + ););

  }

  雙擊表格連接到另一頁

  在itemDataBind事件中

  Code:

  if(eItemItemType == ListItemTypeItem || eItemItemType == ListItemTypeAlternatingItem)

  {

  string orderItemID =emcells[]Text;

  emAttributesAdd(ondblclick locationhref=/ShippedGridaspx?id= + orderItemID + );

  }

  雙擊表格打開新一頁

  Code:

  if(eItemItemType == ListItemTypeItem || eItemItemType == ListItemTypeAlternatingItem)

  {

  string orderItemID =emcells[]Text;

  emAttributesAdd(ondblclick open(/ShippedGridaspx?id= + orderItemID + ));

  }

  表格超連接列傳遞參數

  Code:

  <asp:HyperLinkColumn Target=_blank headertext=ID號 DataTextField=id NavigateUrl=aaaaspx?id=

  <%# DataBinderEval(ContainerDataItem 數據字段)%> & name=<%# DataBinderEval(ContainerDataItem 數據字段)%> />

  表格點擊改變顏色

  Code:

  if (eItemItemType == ListItemTypeItem ||eItemItemType == ListItemTypeAlternatingItem)

  {

  eItemAttributesAdd(onclickthisstylebackgroundColor=#cc;

  lor=buttontext;thisstylecursor=default;);

  }

  寫在DataGrid的_ItemDataBound裡

  Code:

  if (eItemItemType == ListItemTypeItem ||eItemItemType == ListItemTypeAlternatingItem)

  {

  eItemAttributesAdd(onmouseoverthisstylebackgroundColor=#cc;

  lor=buttontext;thisstylecursor=default;);

  eItemAttributesAdd(onmouseoutthisstylebackgroundColor=;lor=;);

  }

  關於日期格式

  日期格式設定

  Code:

  DataFormatString={:yyyyMMdd}

  我覺得應該在itembound事件中

  emscell[你的列]text=DateTimeParse(emscell[你的列]textToString(yyyyMMdd))

  Code:

  獲取錯誤信息並到指定頁面

  不要使用ResponseRedirect而應該使用ServerTransfer

  eg

  Code:

  // in globalasax

  protected void Application_Error(Object sender EventArgs e) {

  if (ServerGetLastError() is HttpUnhandledException)

  ServerTransfer(MyErrorPageaspx);

  //其余的非HttpUnhandledException異常交給ASPNET自己處理就okay了 :)

  }

  Redirect會導致post-back的產生從而丟失了錯誤信息所以頁面導向應該直接在服務器端執行這樣就可以在錯誤處理頁面得到出錯信息並進行相應的處理

  清空Cookie

  Code:

  CookieExpires=[DateTime];

  ResponseCookies(UserName)Expires =

  自定義異常處理

  Code:

  //自定義異常處理類

  using System;

  using SystemDiagnostics;

  namespace MyAppException

  {

  /// <summary>

  /// 從系統異常類ApplicationException繼承的應用程序異常處理類

  /// 自動將異常內容記錄到Windows NT/的應用程序日志

  /// </summary>

  public class AppException:SystemApplicationException

  {

  public AppException()

  {

  if (ApplicationConfigurationEventLogEnabled)LogEvent(出現一個未知錯誤);

  }

  public AppException(string message)

  {

  LogEvent(message);

  }

  public AppException(string messageException innerException)

  {

  LogEvent(message);

  if (innerException != null)

  {

  LogEvent(innerExceptionMessage);

  }

  }

  //日志記錄類

  using System;

  using SystemConfiguration;

  using SystemDiagnostics;

  using SystemIO;

  using SystemText;

  using SystemThreading;

  namespace MyEventLog

  {

  /// <summary>

  /// 事件日志記錄類提供事件日志記錄支持

  /// <remarks>

  /// 定義了個日志記錄方法 (error warning info trace)

  /// </remarks>

  /// </summary>

  public class ApplicationLog

  {

  /// <summary>

  /// 將錯誤信息記錄到Win/NT事件日志中

  /// <param name=message>需要記錄的文本信息</param>

  /// </summary>

  public static void WriteError(String message)

  {

  WriteLog(TraceLevelError message);

  }

  /// <summary>

  /// 將警告信息記錄到Win/NT事件日志中

  /// <param name=message>需要記錄的文本信息</param>

  /// </summary>

  public static void WriteWarning(String message)

  {

  WriteLog(TraceLevelWarning message);

  }

  /// <summary>

  /// 將提示信息記錄到Win/NT事件日志中

  /// <param name=message>需要記錄的文本信息</param>

  /// </summary>

  public static void WriteInfo(String message)

  {

  WriteLog(TraceLevelInfo message);

  }

  /// <summary>

  /// 將跟蹤信息記錄到Win/NT事件日志中

  /// <param name=message>需要記錄的文本信息</param>

  /// </summary>

  public static void WriteTrace(String message)

  {

  WriteLog(TraceLevelVerbose message);

  }

  /// <summary>

  /// 格式化記錄到事件日志的文本信息格式

  /// <param name=ex>需要格式化的異常對象</param>

  /// <param name=catchInfo>異常信息標題字符串</param>

  /// <retvalue>

  /// <para>格式後的異常信息字符串包括異常內容和跟蹤堆棧</para>

  /// </retvalue>

  /// </summary>

  public static String FormatException(Exception ex String catchInfo)

  {

  StringBuilder strBuilder = new StringBuilder();

  if (catchInfo != StringEmpty)

  {

  strBuilderAppend(catchInfo)Append(\r\n);

  }

  strBuilderAppend(exMessage)Append(\r\n)Append(exStackTrace);

  return strBuilderToString();

  }

  /// <summary>

  /// 實際事件日志寫入方法

  /// <param name=level>要記錄信息的級別(errorwarninginfotrace)</param>

  /// <param name=messageText>要記錄的文本</param>

  /// </summary>

  private static void WriteLog(TraceLevel level String messageText)

  {

  try

  {

  EventLogEntryType LogEntryType;

  switch (level)

  {

  case TraceLevelError:

  LogEntryType = EventLogEntryTypeError;

  break;

  case TraceLevelWarning:

  LogEntryType = EventLogEntryTypeWarning;

  break;

  case TraceLevelInfo:

  LogEntryType = EventLogEntryTypeInformation;

  break;

  case TraceLevelVerbose:

  LogEntryType = EventLogEntryTypeSuccessAudit;

  break;

  default:

  LogEntryType = EventLogEntryTypeSuccessAudit;

  break;

  }

  EventLog eventLog = new EventLog(Application ApplicationConfigurationEventLogMachineName ApplicationConfigurationEventLogSourceName );

  //寫入事件日志

  eventLogWriteEntry(messageText LogEntryType);

  }

  catch {} //忽略任何異常

  }

  } //class ApplicationLog

  }

  Panel 橫向滾動縱向自動擴展

  Code:

  <asp:panel ></asp:panel>

  回車轉換成Tab

  ()

  Code:

  <script language=javascript for=document event=onkeydown

  if(eventkeyCode== && eventsrcElementtype!=button && eventsrcElementtype!=submit &&     eventsrcElementtype!=reset && eventsrcElementtype!=&& eventsrcElementtype!=textarea);

  eventkeyCode=;

  </script>

  () //當在有keydown事件的控件上敲回車時變為tab

  Code:

  public void Tab(SystemWeb UIWebControls WebControl webcontrol)

  {

  webcontrolAttributes Add (onkeydown if(eventkeyCode==) eventkeyCode=);

  }

  DataGrid超級連接列

  Code:

  DataNavigateUrlField=字段名 DataNavigateUrlFormatString=x?ID={}

  DataGrid行隨鼠標變色

  Code:

  private void DGzf_ItemDataBound(object sender SystemWebUIWebControlsDataGridItemEventArgs e)

  {

  if (eItemItemType!=ListItemTypeHeader)

  {

  eItemAttributesAdd( onmouseoutthisstylebackgroundColor=\+eItemStyle[BACKGROUNDCOLOR]+\);

  eItemAttributesAdd( onmouseoverthisstylebackgroundColor=\+ #EFFF+\);

  }

  }

  模板列

  Code:

  <ASP:TEMPLATECOLUMN visible=False sortexpression=demo headertext=ID

  <ITEMTEMPLATE>

  <ASP LABEL text=<%# DataBinderEval(ContainerDataItem ArticleID)%> runat=server width=% id=lblColumn />

  </ITEMTEMPLATE>

  </ASP:TEMPLATECOLUMN>

  <ASP:TEMPLATECOLUMN headertext=選中

  <HEADERSTYLE wrap=False horiz></HEADERSTYLE>

  <ITEMTEMPLATE>

  <ASP:CHECKBOX id=chkExport runat=server />

  </ITEMTEMPLATE>

  <EDITITEMTEMPLATE>

  <ASP:CHECKBOX id=chkExportON runat=server enabled=true />

  </EDITITEMTEMPLATE>

  </ASP:TEMPLATECOLUMN>

  後台代碼

  Code:

  protected void CheckAll_CheckedChanged(object sender SystemEventArgs e)

  {

  //改變列的選定實現全選或全不選

  CheckBox chkExport ;

  if( CheckAllChecked)

  {

  foreach(DataGridItem oDataGridItem in MyDataGridItems)

  {

  chkExport = (CheckBox)oDataGridItemFindControl(chkExport);

  chkExportChecked = true;

  }

  }

  else

  {

  foreach(DataGridItem oDataGridItem in MyDataGridItems)

  {

  chkExport = (CheckBox)oDataGridItemFindControl(chkExport);

  chkExportChecked = false;

  }

  }

  }

  數字格式化

  Code:

  【<%#ContainerDataItem(price)%>的結果是怎樣格式化為?】

  <%#ContainerDataItem(price{:¥###})%>

  int i=;

  string s=iToString(######);

  日期格式化

  【aspx頁面內<%# DataBinderEval(ContainerDataItemCompany_Ureg_Date)%>

  顯示為 ::

  我只想要

  Code:

  <%# DataBinderEval(ContainerDataItemCompany_Ureg_Date{:yyyyMd})%>

  應該如何改?

  【格式化日期】

  取出來一般是

  Code:

  object((DateTime)objectFromDB)ToString(yyyyMMdd);

  【日期的驗證表達式】

  A以下正確的輸入格式 [] [ :: pm] [//]

  ^((\d{}(([][])|([][]))[\\/\s]?((((?[])|([]))[\\/\s]?((?[])|([][])|([])))|(((?[])|())[\\/\s]?((?[])|([][])|()))|(?[\\/\s]?((?[])|([][])))))|(\d{}(([][])|([][]))[\\/\s]?((((?[])|([]))[\\/\s]?((?[])|([][])|([])))|(((?[])|())[\\/\s]?((?[])|([][])|()))|(?[\\/\s]?((?[])|([])|([]))))))(\s(((?[])|([]))\:([][])((\s)|(\:([][])\s))([AM|PM|am|pm]{})))?$

  B以下正確的輸入格式[] [ ] [//]

  ^\d{}[\\/\s]?(((([])|([]))[\\/\s]?(([][])|([])))|((([])|())[\\/\s]?(([][])|()))|([\\/\s]?[][]))$

  【大小寫轉換】

  HttpUtilityHtmlEncode(string);

  HttpUtilityHtmlDecode(string);

  如何設定全局變量

  Globalasax中

  Application_Start()事件中

  添加Application[屬性名] = xxx;

  就是你的全局變量

  怎樣作到HyperLinkColumn生成的連接後點擊連接打開新窗口?

  HyperLinkColumn有個屬性Target將器值設置成_blank即可(Target=_blank)

  【ASPNETMENU】點擊菜單項彈出新窗口

  在你的menuDataxml文件的菜單項中加入URLTarget=_blank

  Code:

  <?xml version= encoding=GB?>

  <MenuData ImagesBaseURL=images/

  <MenuGroup>

  <MenuItem Label=內參信息 URL=Infomationaspx

  <MenuGroup ID=BBC

  <MenuItem Label=公告信息 URL=Infomationaspx URLTarget=_blank LeftIcon=filegif/>

  <MenuItem Label=編制信息簡報 URL=NewInfoaspx LeftIcon=filegif />

  最好將你的aspnetmenu升級到

  讀取DataGrid控件TextBox值

  Code:

  foreach(DataGrid dgi in yourDataGridItems)

  {

  TextBox tb = (TextBox)dgiFindControl(yourTextBoxId);

  tbText

  }

  在DataGrid中有個模板列包含Textbox分別為 DG_ShuLiang (數量) DG_DanJian(單價) DG_JinE(金額)分別在要求在錄入數量及單價的時候自動算出金額即:數量*單價=金額還要求錄入時限制為 數值型我如何用客戶端腳本實現這個功能?

  Code:

  <asp:TemplateColumn HeaderText=數量

  <ItemTemplate>

  <asp:TextBox id=ShuLiang runat=server Text=<%# DataBinderEval(ContainerDataItemDG_ShuLiang)%>

  />

  <asp:RegularExpressionValidator id=revS runat=server C ErrorMessage=must be integer Validati />

  </ItemTemplate>

  </asp:TemplateColumn>

  <asp:TemplateColumn HeaderText=單價

  <ItemTemplate>

  <asp:TextBox id=DanJian runat=server Text=<%# DataBinderEval(ContainerDataItemDG_DanJian)%>

  />

  <asp:RegularExpressionValidator id=revS runat=server C ErrorMessage=must be numeric Validati />

  </ItemTemplate>

  </asp:TemplateColumn>

  <asp:TemplateColumn HeaderText=金額

  <ItemTemplate>

  <asp:TextBox id=JinE runat=server Text=<%# DataBinderEval(ContainerDataItemDG_JinE)%> />

  </ItemTemplate>

  </asp:TemplateColumn><script language=javascript

  function DoCal()

  {

  var e = eventsrcElement;

  var row = eparentNodeparentNode;

  var txts = rowalltags(INPUT);

  if (!txtslength || txtslength < )

  return;

  var q = txts[txtslength]value;

  var p = txts[txtslength]value;

  if (isNaN(q) || isNaN(p))

  return;

  q = parseInt(q);

  p = parseFloat(p);

  txts[txtslength]value = (q * p)toFixed();

  }

  </script>

  datagrid選定比較底下的行時為什麼總是刷新一下然後就滾動到了最上面剛才選定的行因屏幕的關系就看不到了

  Code:

  page_load

  pagesmartNavigation=true

  在Datagrid中修改數據當點擊編輯鍵時數據出現在文本框中怎麼控制文本框的大小 ?

  Code:

  private void DataGrid_ItemDataBound(obj senderDataGridItemEventArgs e)

  {

  for(int i=;i<eItemCellsCount;i++)

  if(eItemItemType==ListItemTypeEditType)

  {

  eItemCellsAttributesAdd(Width px)

  }

  }

  對話框

  Code:

  private static string ScriptBegin = <script language=\JavaScript\;

  private static string ScriptEnd = </script>;

  public static void ConfirmMessageBox(string PageTargetstring Content)

  {

  string C+Content+);+if(retValue){windowlocation=+PageTarget+;};

  ConfirmContent=ScriptBegin + ConfirmContent + ScriptEnd;

  Page ParameterPage = (Page)SystemWebHttpContextCurrentHandler;

  ParameterPageRegisterStartupScript(confirmConfirmContent);

  //ResponseWrite

  (strScript);

  }

   將時間格式化string aa=DateTimeNowToString(yyyy年MM月dd日);

   取當前年月日時分秒

  currentTime=SystemDateTimeNow;

   取當前年

  int 年= DateTimeNowYear;

   取當前月

  int 月= DateTimeNowMonth;

   取當前日

  int 日= DateTimeNowDay;

   取當前時

  int 時= DateTimeNowHour;

   取當前分

  int 分= DateTimeNowMinute;

   取當前秒

  int 秒= DateTimeNowSecond;

   取當前毫秒

  int 毫秒= DateTimeNowMillisecond;

  .自定義分頁代碼

  先定義變量

  Code:

  public static int pageCount; //總頁面數

  public static int curPageIndex=; //當前頁面

  下一頁

  if(DataGridCurrentPageIndex < (DataGridPageCount ))

  {

  DataGridCurrentPageIndex += ;

  curPageIndex+=;

  }

  bind(); // DataGrid數據綁定函數

  上一頁

  if(DataGridCurrentPageIndex >)

  {

  DataGridCurrentPageIndex += ;

  curPageIndex=;

  }

  bind(); // DataGrid數據綁定函數

  直接頁面跳轉

  int a=intParse(JumpPageValueTrim());//JumpPageValueTrim()為跳轉值

  if(a<DataGridPageCount)

  {

  thisDataGridCurrentPageIndex=a;

  }

  bind();

  .DataGrid使用

  添加刪除確認

  Code:

  private void DataGrid_ItemCreated(object sender SystemWebUIWebControlsDataGridItemEventArgs e)

  {

  foreach(DataGridItem di in thisDataGridItems)

  {

  if(diItemType==ListItemTypeItem||diItemType==ListItemTypeAlternatingItem)

  {

  ((LinkButton)diCells[]Controls[])AttributesAdd(onclickreturn confirm(確認刪除此項嗎?););

  }

  }

  }

  樣式交替

  Code:

  ListItemType itemType = eItemItemType;

  if (itemType == ListItemTypeItem )

  {

  eItemAttributes[onmouseout] = javascript:thisstylebackgroundColor=#FFFFFF;;

  eItemAttributes[onmouseover] = javascript:thisstylebackgroundColor=#dece;cursor=hand; ;

  }

  else if( itemType == ListItemTypeAlternatingItem)

  {

  eItemAttributes[onmouseout] = javascript:thisstylebackgroundColor=#adc;;

  eItemAttributes[onmouseover] = javascript:thisstylebackgroundColor=#dece;cursor=hand; ;

  }

  添加一個編號列

  Code:

  DataTable dt= cExecuteRtnTableForAccess(sqltxt); //執行sql返回的DataTable

  DataColumn dc=dtColumnsAdd(numberSystemTypeGetType(SystemString));

  for(int i=;i<dtRowsCount;i++)

  {

  dtRows[number]=(i+)ToString();

  }

  DataGridDataSource=dt;

  DataGridDataBind();

  DataGrid中添加一個CheckBox頁面中添加一個全選框

  private void CheckBox_CheckedChanged(object sender SystemEventArgs e)

  {

  foreach(DataGridItem thisitem in DataGridItems)

  {

  ((CheckBox)thisitemCells[]Controls[])Checked=CheckBoxChecked;

  }

  }

  將當前頁面中DataGrid顯示的數據全部刪除

  Code:

  foreach(DataGridItem thisitem in DataGridItems)

  {

  if(((CheckBox)thisitemCells[]Controls[])Checked)

  {

  string strloginid= DataGridDataKeys[thisitemItemIndex]ToString();

  Del (strloginid); //刪除函數

  }

  }

  .當文件在不同目錄下需要獲取數據庫連接字符串(如果連接字符串放在nfig然後在Globalasax中初始化)

  在Application_Start中添加以下代碼

  Code:

  Application[ConnStr]=thisContextRequestPhysicalApplicationPath+ConfigurationSettings

  AppSettings[ConnStr]ToString();

  . 變量ToString()

  字符型轉換 轉為字符串

  Code:

  ToString(n); //生成

  ToString(C); //生成 ¥

  ToString(e); //生成 e+

  ToString(f); //生成

  ToString(x); //生成 (進制)

  ToString(p); //生成 %

  變量Substring(參數參數);

  截取字串的一部分參數為左起始位數參數為截取幾位string s = strSubstring();

  .在自己的網站上登陸其他網站(如果你的頁面是通過嵌套方式的話因為一個頁面只能有一個FORM這時可以導向另外一個頁面再提交登陸信息)

  Code:

  <SCRIPT language=javascript

  <!

  function gook(pws)

  {

  frmsubmit();

  }

  //

  </SCRIPT> <body leftMargin= topMargin=  marginwidth= marginheight=

  <form name=frm action= method=post

  <tr>

  <td>

  <input id=f_user type=hidden size= name=f_user runat=server

  <input id=f_domain type=hidden size= name=f_domain runat=server

  <input class=box id=f_pass type=hidden size= name=pwshow runat=server

  <INPUT id=lng type=hidden maxLength= size= value= name=lng

  <INPUT id=tem type=hidden size= value= name=tem

  </td>

  </tr>

  </form>

  文本框的名稱必須是你要登陸的網頁上的名稱如果源碼不行可以用vsniffer 看看

  下面是獲取用戶輸入的登陸信息的代碼

  Code:

  string name;

  name=RequestQueryString[EmailName];

  try

  {

  int a=nameIndexOf(@nameLength);

  f_userValue=nameSubstring(a);

  f_domainValue=nameSubstring(a+nameLength(a+));

  f_passValue=RequestQueryString[Psw];

  }

  catch

  {

  ScriptAlert(錯誤的郵箱!);

  ServerTransfer(indexaspx);

  }

  datagrid分頁中如果刪除時出現超出索引

  Code:

  public void jumppage(SystemWebUIWebControlsDataGrid dg)

  {

  int int_PageLess; //定義頁面跳轉的頁數

  //如果當前頁是最後一頁

  if(dgCurrentPageIndex == dgPageCount)

  {

  //如果就只有一頁

  if(dgCurrentPageIndex == )

  {

  //刪除後頁面停在當前頁

  dgCurrentPageIndex = dgPageCount;

  }

  else

  {

  //如果最後一頁只有一條記錄

  if((dgItemsCount % dgPageSize == ) || dgPageSize == )

  {

  //把最後一頁最後一條記錄刪除後頁面應跳轉到前一頁

  int_PageLess = ;

  }

  else //如果最後一頁的記錄數大於那麼在最後一頁刪除記錄後仍然停在當前頁

  {

  int_PageLess = ;

  }

  dgCurrentPageIndex = dgPageCount int_PageLess;

  }

  }

  }

  警告窗口

  /**//// <summary>

  /// 服務器端彈出alert對話框

  /// </summary>

  /// <param name=str_Message>提示信息例子不能為空!</param>

  /// <param name=page>Page類</param>

  Code:

  public void Alert(string str_MessagePage page)

  {

  pageRegisterStartupScript(<script>alert(+str_Message+);</script>);

  }

  重載此警告窗口使某控件獲得焦點

  Code:

  /**//// <summary>

  /// 服務器端彈出alert對話框並使控件獲得焦點

  /// </summary>

  /// <param name=str_Ctl_Name>獲得焦點控件Id值比如txt_Name</param>

  /// <param name=str_Message>提示信息例子請輸入您姓名!</param>

  /// <param name=page>Page類</param>

  public void Alert(string str_Ctl_Namestring str_MessagePage page)

  {

  pageRegisterStartupScript(<script>alert(+str_Message+);documentforms()+str_Ctl_Name+focus(); documentforms()+str_Ctl_Name+select();</script>);

  }

  確認對話框

  Code:

  /**//// <summary>

  /// 服務器端彈出confirm對話框

  /// </summary>

  /// <param name=str_Message>提示信息例子您是否確認刪除!</param>

  /// <param name=btn>隱藏Botton按鈕Id值比如btn_Flow</param>

  /// <param name=page>Page類</param>

  public void Confirm(string str_Messagestring btnPage page)

  {

  pageRegisterStartupScript(<script> if (confirm(+str_Message+)==true){documentforms()+btn+click();}</script>);

  }

  重載確認對話框點擊確定觸發一個隱藏按鈕事件點擊取消觸發一個隱藏按鈕事件

  Code:

  /**//// <summary>

  /// 服務器端彈出confirm對話框詢問用戶准備轉向那些操作包括確定取消時的操作

  /// </summary>

  /// <param name=str_Message>提示信息比如成功增加數據單擊\確定\按鈕填寫流程單擊\取消\修改數據</param>

  /// <param name=btn_Redirect_Flow>確定按鈕id值</param>

  /// <param name=btn_Redirect_Self>取消按鈕id值</param>

  /// <param name=page>Page類</param>

  public void Confirm(string str_Messagestring btn_Redirect_Flowstring btn_Redirect_SelfPage page)

  {

  pageRegisterStartupScript(<script> if (confirm(+str_Message+)==true){documentforms()+btn_Redirect_Flow+click();}else{documentforms()+btn_Redirect_Self+click();}</script>);

  }

  獲得焦點

  Code:

  /**//// <summary>

  /// 使控件獲得焦點

  /// </summary>

  /// <param name=str_Ctl_Name>獲得焦點控件Id值比如txt_Name</param>

  /// <param name=page>Page類</param>

  public void GetFocus(string str_Ctl_NamePage page)

  {

  pageRegisterStartupScript(<script>documentforms()+str_Ctl_Name+focus(); documentforms()+str_Ctl_Name+select();</script>);

  }

  子窗體返回主窗體

  Code:

  **////<summary>

  ///名稱redirect

  ///功能子窗體返回主窗體

  ///參數url

  ///返回值

  ///</summary>

  public void redirect(string urlPage page)

  {

  if ( Session[IfDefault]!=(object)Default)

  {

  pageRegisterStartupScript(<script>windowtopdocumentlocation+url+;</script>);

  }

  }

  判斷是否為數字

  Code:

  /**//// <summary>

  /// 名稱IsNumberic

  /// 功能判斷輸入的是否是數字

  /// 參數string oText源文本

  /// 返回值 bool true:是 false:否

  /// </summary>

  public bool IsNumberic(string oText)

  {

  try

  {

  int var=ConvertToInt (oText);

  return true;

  }

  catch

  {

  return false;

  }

  }

  獲得字符串實際長度(包括中文字符)

  Code:

  //獲得字符串oString的實際長度

  public int StringLength(string oString)

  {

  byte[] strArray=SystemText EncodingDefault GetBytes (oString);

  int res=strArrayLength ;

  return res;

  }


From:http://tw.wingwit.com/Article/program/net/201311/12254.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.