国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

絕對精華:ASP.NET常用的三十三種實用代碼

2024-07-10 13:08:22
字體:
來源:轉載
供稿:網友
  1. 打開新的窗口并傳送參數:

  傳送參數:

response.write("<script>window.open(’*.aspx?id="+this.dropdownlist1.selectindex+"&id1="+...+"’)</script>")


  接收參數:

string a = request.querystring("id");
string b = request.querystring("id1");


  2.為按鈕添加對話框

button1.attributes.add("onclick","return confirm(’確認?’)");
button.attributes.add("onclick","if(confirm(’are you sure...?’)){return true;}else{return false;}")


  3.刪除表格選定記錄

int intempid = (int)mydatagrid.datakeys[e.item.itemindex];
string deletecmd = "delete from employee where emp_id = " + intempid.tostring()


  4.刪除表格記錄警告

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("onclick","return confirm(’您是否確定要刪除這條信息’);");
   break;
  default:
   break;
 }

}


  5.點擊表格行鏈接另一頁

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("onclick","window.open(’default.aspx?id=" + e.item.cells[0].text + "’);");
}


  雙擊表格連接到另一頁

  在itemdatabind事件中

if(e.item.itemtype == listitemtype.item || e.item.itemtype == listitemtype.alternatingitem)
{
 string orderitemid =e.item.cells[1].text;
 ...
 e.item.attributes.add("ondblclick", "location.href=’../shippedgrid.aspx?id=" + orderitemid + "’");
}


  雙擊表格打開新一頁

if(e.item.itemtype == listitemtype.item || e.item.itemtype == listitemtype.alternatingitem)
{
 string orderitemid =e.item.cells[1].text;
 ...
 e.item.attributes.add("ondblclick", "open(’../shippedgrid.aspx?id=" + orderitemid + "’)");
}


  ★特別注意:【?id=】 處不能為 【?id =】

  6.表格超連接列傳遞參數

<asp:hyperlinkcolumn target="_blank" headertext="id號" datatextfield="id" navigateurl="aaa.aspx?id=’
 <%# databinder.eval(container.dataitem, "數據字段1")%>’ & name=’<%# databinder.eval(container.dataitem, "數據字段2")%>’ />


  7.表格點擊改變顏色

if (e.item.itemtype == listitemtype.item ||e.item.itemtype == listitemtype.alternatingitem)
{
 e.item.attributes.add("onclick","this.style.backgroundcolor=’#99cc00’;
    this.style.color=’buttontext’;this.style.cursor=’default’;");
}


  寫在datagrid的_itemdatabound里

if (e.item.itemtype == listitemtype.item ||e.item.itemtype == listitemtype.alternatingitem)
{
e.item.attributes.add("onmouseover","this.style.backgroundcolor=’#99cc00’;
   this.style.color=’buttontext’;this.style.cursor=’default’;");
e.item.attributes.add("onmouseout","this.style.backgroundcolor=’’;this.style.color=’’;");
}



  8.關于日期格式

  日期格式設定

dataformatstring="{0:yyyy-mm-dd}"


  我覺得應該在itembound事件中

e.items.cell["你的列"].text=datetime.parse(e.items.cell["你的列"].text.tostring("yyyy-mm-dd"))


  9.獲取錯誤信息并到指定頁面

  不要使用response.redirect,而應該使用server.transfer

  e.g

// in global.asax
protected void application_error(object sender, eventargs e) {
if (server.getlasterror() is httpunhandledexception)
server.transfer("myerrorpage.aspx");

//其余的非httpunhandledexception異常交給asp.net自己處理就okay了 :)
}


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

  10.清空cookie

cookie.expires=[datetime];
response.cookies("username").expires = 0


  11.自定義異常處理

//自定義異常處理類
using system;
using system.diagnostics;

namespace myappexception
{
 /// <summary>
 /// 從系統異常類applicationexception繼承的應用程序異常處理類。
 /// 自動將異常內容記錄到windows nt/2000的應用程序日志
 /// </summary>
 public class appexception:system.applicationexception
 {
  public appexception()
  {
   if (applicationconfiguration.eventlogenabled)logevent("出現一個未知錯誤。");
  }

 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="message">需要記錄的文本信息</param>
   /// </summary>
   public static void writeerror(string message)
   {
    writelog(tracelevel.error, message);
   }

   /// <summary>
   /// 將警告信息記錄到win2000/nt事件日志中
   /// <param name="message">需要記錄的文本信息</param>
   /// </summary>
   public static void writewarning(string message)
   {
    writelog(tracelevel.warning, message);  
   }

   /// <summary>
   /// 將提示信息記錄到win2000/nt事件日志中
   /// <param name="message">需要記錄的文本信息</param>
   /// </summary>
   public static void writeinfo(string message)
   {
    writelog(tracelevel.info, message);
   }
   /// <summary>
   /// 將跟蹤信息記錄到win2000/nt事件日志中
   /// <param name="message">需要記錄的文本信息</param>
   /// </summary>
   public static void writetrace(string message)
   {
    writelog(tracelevel.verbose, 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 != string.empty)
    {
     strbuilder.append(catchinfo).append("/r/n");
    }
    strbuilder.append(ex.message).append("/r/n").append(ex.stacktrace);
    return strbuilder.tostring();
   }

   /// <summary>
   /// 實際事件日志寫入方法
   /// <param name="level">要記錄信息的級別(error,warning,info,trace).</param>
   /// <param name="messagetext">要記錄的文本.</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("application", applicationconfiguration.eventlogmachinename, applicationconfiguration.eventlogsourcename );
     //寫入事件日志
     eventlog.writeentry(messagetext, logentrytype);

    }
   catch {} //忽略任何異常
  }
 } //class applicationlog
}

  12.panel 橫向滾動,縱向自動擴展

<asp:panel ></asp:panel>


  13.回車轉換成tab

<script language="javascript" for="document" event="onkeydown">
 if(event.keycode==13 && event.srcelement.type!=’button’ && event.srcelement.type!=’submit’ &&     event.srcelement.type!=’reset’ && event.srcelement.type!=’’&& event.srcelement.type!=’textarea’);
   event.keycode=9;
</script>

onkeydown="if(event.keycode==13) event.keycode=9"


  14.datagrid超級連接列

datanavigateurlfield="字段名" datanavigateurlformatstring="http://xx/inc/delete.aspx?id={0}"


  15.datagrid行隨鼠標變色

private void dgzf_itemdatabound(object sender, system.web.ui.webcontrols.datagriditemeventargs e)
{
 if (e.item.itemtype!=listitemtype.header)
 {
  e.item.attributes.add( "onmouseout","this.style.backgroundcolor=/""+e.item.style["background-color"]+"/"");
  e.item.attributes.add( "onmouseover","this.style.backgroundcolor=/""+ "#eff3f7"+"/"");
 }
}


  16.模板列

<asp:templatecolumn visible="false" sortexpression="demo" headertext="id">
<itemtemplate>
<asp:label text=’<%# databinder.eval(container.dataitem, "articleid")%>’ runat="server" width="80%" id="lblcolumn" />
</itemtemplate>
</asp:templatecolumn>

<asp:templatecolumn headertext="選中">
<headerstyle wrap="false" horizontalalign="center"></headerstyle>
<itemtemplate>
<asp:checkbox id="chkexport" runat="server" />
</itemtemplate>
<edititemtemplate>
<asp:checkbox id="chkexporton" runat="server" enabled="true" />
</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("chkexport");
   chkexport.checked = true;
  }
 }
 else
 {
  foreach(datagriditem odatagriditem in mydatagrid.items)
  {
   chkexport = (checkbox)odatagriditem.findcontrol("chkexport");
   chkexport.checked = false;
  }
 }
}


  17.數字格式化

  【<%#container.dataitem("price")%>的結果是500.0000,怎樣格式化為500.00?】

<%#container.dataitem("price","{0:¥#,##0.00}")%>

int i=123456;
string s=i.tostring("###,###.00");

  18.日期格式化

  【aspx頁面內:<%# databinder.eval(container.dataitem,"company_ureg_date")%>

  顯示為: 2004-8-11 19:44:28

  我只想要:2004-8-11 】

<%# databinder.eval(container.dataitem,"company_ureg_date","{0:yyyy-m-d}")%>


  應該如何改?

  【格式化日期】

  取出來,一般是object((datetime)objectfromdb).tostring("yyyy-mm-dd");

  【日期的驗證表達式】

  a.以下正確的輸入格式: [2004-2-29], [2004-02-29 10:29:39 pm], [2004/12/31]

^((/d{2}(([02468][048])|([13579][26]))[/-///s]?((((0?[13578])|(1[02]))[/-///s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[/-///s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[/-///s]?((0?[1-9])|([1-2][0-9])))))|(/d{2}(([02468][1235679])|([13579][01345789]))[/-///s]?((((0?[13578])|(1[02]))[/-///s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[/-///s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[/-///s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(/s(((0?[1-9])|(1[0-2]))/:([0-5][0-9])((/s)|(/:([0-5][0-9])/s))([am|pm|am|pm]{2,2})))?$


  b.以下正確的輸入格式:[0001-12-31], [9999 09 30], [2002/03/03]

^/d{4}[/-///s]?((((0[13578])|(1[02]))[/-///s]?(([0-2][0-9])|(3[01])))|(((0[469])|(11))[/-///s]?(([0-2][0-9])|(30)))|(02[/-///s]?[0-2][0-9]))$


  【大小寫轉換】

httputility.htmlencode(string);
httputility.htmldecode(string)


  19.如何設定全局變量

  global.asax中

  application_start()事件中

  添加application[屬性名] = xxx;

  就是你的全局變量

  20.怎樣作到hyperlinkcolumn生成的連接后,點擊連接,打開新窗口?

  hyperlinkcolumn有個屬性target,將器值設置成"_blank"即可.(target="_blank")

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

  在你的menudata.xml文件的菜單項中加入urltarget="_blank",如:

<?xml version="1.0" encoding="gb2312"?>
<menudata imagesbaseurl="images/">
<menugroup>
<menuitem label="內參信息" url="infomation.aspx" >
<menugroup id="bbc">
<menuitem label="公告信息" url="infomation.aspx" urltarget="_blank" lefticon="file.gif"/>
<menuitem label="編制信息簡報" url="newinfo.aspx" lefticon="file.gif" />
......


  最好將你的aspnetmenu升級到1.2版

  21.讀取datagrid控件textbox值

foreach(datagrid dgi in yourdatagrid.items)
{
 textbox tb = (textbox)dgi.findcontrol("yourtextboxid");
 tb.text....
}


  23.在datagrid中有3個模板列包含textbox分別為 dg_shuliang (數量) dg_danjian(單價) dg_jine(金額)分別在5.6.7列,要求在錄入數量及單價的時候自動算出金額即:數量*單價=金額還要求錄入時限制為 數值型.我如何用客戶端腳本實現這個功能?

  〖思歸〗

<asp:templatecolumn headertext="數量">
<itemtemplate>
<asp:textbox id="shuliang" runat=’server’ text=’<%# databinder.eval(container.dataitem,"dg_shuliang")%>’
onkeyup="javascript:docal()"
/>

<asp:regularexpressionvalidator id="revs" runat="server" controltovalidate="shuliang" errormessage="must be integer" validationexpression="^/d+$" />
</itemtemplate>
</asp:templatecolumn>

<asp:templatecolumn headertext="單價">
<itemtemplate>
<asp:textbox id="danjian" runat=’server’ text=’<%# databinder.eval(container.dataitem,"dg_danjian")%>’
onkeyup="javascript:docal()"
/>

<asp:regularexpressionvalidator id="revs2" runat="server" controltovalidate="danjian" errormessage="must be numeric" validationexpression="^/d+(/./d*)?$" />

</itemtemplate>
</asp:templatecolumn>

<asp:templatecolumn headertext="金額">
<itemtemplate>
<asp:textbox id="jine" runat=’server’ text=’<%# databinder.eval(container.dataitem,"dg_jine")%>’ />
</itemtemplate>
</asp:templatecolumn><script language="javascript">
function docal()
{
 var e = event.srcelement;
 var row = e.parentnode.parentnode;
 var txts = row.all.tags("input");
 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>

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

page_load
page.smartnavigation=true


  25.在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[i].attributes.add("width", "80px")
  }
}


  26.對話框

private static string scriptbegin = "<script language=/"javascript/">";
private static string scriptend = "</script>";

public static void confirmmessagebox(string pagetarget,string content)
{
 string confirmcontent="var retvalue=window.confirm(’"+content+"’);"+"if(retvalue){window.location=’"+pagetarget+"’;}";

 confirmcontent=scriptbegin + confirmcontent + scriptend;

 page parameterpage = (page)system.web.httpcontext.current.handler;
 parameterpage.registerstartupscript("confirm",confirmcontent);
 //response.write(strscript);
}


  27. 將時間格式化: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;


  28.自定義分頁代碼:

  先定義變量 :

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

  29.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("onclick","return confirm(’確認刪除此項嗎?’);");
  }
 }
}


  樣式交替:

listitemtype itemtype = e.item.itemtype;

if (itemtype == listitemtype.item )
{
 e.item.attributes["onmouseout"] = "javascript:this.style.backgroundcolor=’#ffffff’;";
 e.item.attributes["onmouseover"] = "javascript:this.style.backgroundcolor=’#d9ece1’;cursor=’hand’;" ;
}
else if( itemtype == listitemtype.alternatingitem)
{
 e.item.attributes["onmouseout"] = "javascript:this.style.backgroundcolor=’#a0d7c4’;";
 e.item.attributes["onmouseover"] = "javascript:this.style.backgroundcolor=’#d9ece1’;cursor=’hand’;" ;
}


  添加一個編號列:

datatable dt= c.executertntableforaccess(sqltxt); //執行sql返回的datatable
datacolumn dc=dt.columns.add("number",system.type.gettype("system.string"));

for(int i=0;i<dt.rows.count;i++)
{
 dt.rows[i]["number"]=(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); //刪除函數
 }
}


  30.當文件在不同目錄下,需要獲取數據庫連接字符串(如果連接字符串放在web.config,然后在global.asax中初始化)

  在application_start中添加以下代碼:

application["connstr"]=this.context.request.physicalapplicationpath+configurationsettings.
   appsettings["connstr"].tostring();


  31. 變量.tostring()

  字符型轉換 轉為字符串

12345.tostring("n"); //生成 12,345.00
12345.tostring("c"); //生成 ¥12,345.00
12345.tostring("e"); //生成 1.234500e+004
12345.tostring("f4"); //生成 12345.0000
12345.tostring("x"); //生成 3039 (16進制)
12345.tostring("p"); //生成 1,234,500.00%


  32、變量.substring(參數1,參數2);

  截取字串的一部分,參數1為左起始位數,參數2為截取幾位。 如:string s1 = str.substring(0,2);

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

<script language="javascript">
<!--
 function gook(pws)
 {
  frm.submit();
 }
//-->

</script> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<form name="frm" action=" http://220.194.55.68:6080/login.php?retid=7259 " method="post">
<tr>
<td>
<input id="f_user" type="hidden" size="1" name="f_user" runat="server">
<input id="f_domain" type="hidden" size="1" name="f_domain" runat="server">
<input class="box" id="f_pass" type="hidden" size="1" name="pwshow" runat="server">

<input id="lng" type="hidden" maxlength="20" size="1" value="5" name="lng">
<input id="tem" type="hidden" size="1" value="2" name="tem">

</td>

</tr>

</form>


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

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

string name;
name=request.querystring["emailname"];

try
{
 int a=name.indexof("@",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["psw"];
}

catch
{
 script.alert("錯誤的郵箱!");
 server.transfer("index.aspx");
}

菜鳥學堂:
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宜宾县| 尼木县| 东平县| 沈丘县| 喀喇| 吴江市| 新余市| 城市| 奇台县| 贵德县| 疏勒县| 浦县| 柳州市| 漳平市| 乐平市| 合作市| 札达县| 灵山县| 黄骅市| 蒙山县| 黄大仙区| 巴南区| 启东市| 长葛市| 木里| 罗城| 西贡区| 石泉县| 宁都县| 望城县| 平果县| 武汉市| 南安市| 连城县| 汽车| 临澧县| 若尔盖县| 图片| 安岳县| 莫力| 黑龙江省|