DbHelper的數(shù)據(jù)操作類_第1頁
DbHelper的數(shù)據(jù)操作類_第2頁
DbHelper的數(shù)據(jù)操作類_第3頁
DbHelper的數(shù)據(jù)操作類_第4頁
DbHelper的數(shù)據(jù)操作類_第5頁
已閱讀5頁,還剩12頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

./其實(shí),微軟的企業(yè)庫中有一個非常不錯的數(shù)據(jù)操作類了.但是,不少公司<起碼我遇到的幾個...>,對一些"封裝"了些什么的東西不太敢用,雖然我推薦過微軟的企業(yè)庫框架了...但是還是要"評估"...一評就是幾個月...而且,一些公司有的根本就是裸開發(fā),或者自己封裝的數(shù)據(jù)庫操作類非常別扭,很不好用.

這里我給大家共享一個我參照企業(yè)庫中的數(shù)據(jù)操作組件編碼風(fēng)格寫的數(shù)據(jù)庫操作類,對使用它的程序員來說,編碼是很舒服滴<起碼我覺得很好撒>.以下是代碼,很簡單的,沒有做任何多余的封裝,只是改變了ADO.NET的編碼步驟,方便了具體開發(fā)數(shù)據(jù)庫操作代碼的程序員.usingSystem;usingSystem.Data;usingSystem.Data.Common;usingSystem.Configuration;publicclassDbHelper{privatestaticstringdbProviderName=ConfigurationManager.AppSettings["DbHelperProvider"];privatestaticstringdbConnectionString=ConfigurationManager.AppSettings["DbHelperConnectionString"];privateDbConnectionconnection;publicDbHelper<>{this.connection=CreateConnection<DbHelper.dbConnectionString>;}publicDbHelper<stringconnectionString>{this.connection=CreateConnection<connectionString>;}publicstaticDbConnectionCreateConnection<>{DbProviderFactorydbfactory=DbProviderFactories.GetFactory<DbHelper.dbProviderName>;DbConnectiondbconn=dbfactory.CreateConnection<>;dbconn.ConnectionString=DbHelper.dbConnectionString;returndbconn;}publicstaticDbConnectionCreateConnection<stringconnectionString>{DbProviderFactorydbfactory=DbProviderFactories.GetFactory<DbHelper.dbProviderName>;DbConnectiondbconn=dbfactory.CreateConnection<>;dbconn.ConnectionString=connectionString;returndbconn;}publicDbCommandGetStoredProcCommond<stringstoredProcedure>{DbCommanddbCommand=connection.CreateCommand<>;dbCommand.CommandText=storedProcedure;dbCommand.CommandType=CommandType.StoredProcedure;returndbCommand;}publicDbCommandGetSqlStringCommond<stringsqlQuery>{DbCommanddbCommand=connection.CreateCommand<>;dbCommand.CommandText=sqlQuery;dbCommand.CommandType=CommandType.Text;returndbCommand;}增加參數(shù)#region增加參數(shù)publicvoidAddParameterCollection<DbCommandcmd,DbParameterCollectiondbParameterCollection>{foreach<DbParameterdbParameterindbParameterCollection>{cmd.Parameters.Add<dbParameter>;}}publicvoidAddOutParameter<DbCommandcmd,stringparameterName,DbTypedbType,intsize>{DbParameterdbParameter=cmd.CreateParameter<>;dbParameter.DbType=dbType;dbParameter.ParameterName=parameterName;dbParameter.Size=size;dbParameter.Direction=ParameterDirection.Output;cmd.Parameters.Add<dbParameter>;}publicvoidAddInParameter<DbCommandcmd,stringparameterName,DbTypedbType,objectvalue>{DbParameterdbParameter=cmd.CreateParameter<>;dbParameter.DbType=dbType;dbParameter.ParameterName=parameterName;dbParameter.Value=value;dbParameter.Direction=ParameterDirection.Input;cmd.Parameters.Add<dbParameter>;}publicvoidAddReturnParameter<DbCommandcmd,stringparameterName,DbTypedbType>{DbParameterdbParameter=cmd.CreateParameter<>;dbParameter.DbType=dbType;dbParameter.ParameterName=parameterName;dbParameter.Direction=ParameterDirection.ReturnValue;cmd.Parameters.Add<dbParameter>;}publicDbParameterGetParameter<DbCommandcmd,stringparameterName>{returncmd.Parameters[parameterName];}#endregion執(zhí)行#region執(zhí)行publicDataSetExecuteDataSet<DbCommandcmd>{DbProviderFactorydbfactory=DbProviderFactories.GetFactory<DbHelper.dbProviderName>;DbDataAdapterdbDataAdapter=dbfactory.CreateDataAdapter<>;dbDataAdapter.SelectCommand=cmd;DataSetds=newDataSet<>;dbDataAdapter.Fill<ds>;returnds;}publicDataTableExecuteDataTable<DbCommandcmd>{DbProviderFactorydbfactory=DbProviderFactories.GetFactory<DbHelper.dbProviderName>;DbDataAdapterdbDataAdapter=dbfactory.CreateDataAdapter<>;dbDataAdapter.SelectCommand=cmd;DataTabledataTable=newDataTable<>;dbDataAdapter.Fill<dataTable>;returndataTable;}publicDbDataReaderExecuteReader<DbCommandcmd>{cmd.Connection.Open<>;DbDataReaderreader=cmd.ExecuteReader<CommandBehavior.CloseConnection>;returnreader;}publicintExecuteNonQuery<DbCommandcmd>{cmd.Connection.Open<>;intret=cmd.ExecuteNonQuery<>;cmd.Connection.Close<>;returnret;}publicobjectExecuteScalar<DbCommandcmd>{cmd.Connection.Open<>;objectret=cmd.ExecuteScalar<>;cmd.Connection.Close<>;returnret;}#endregion#region執(zhí)行事務(wù)publicDataSetExecuteDataSet<DbCommandcmd,Transt>{cmd.Connection=t.DbConnection;cmd.Transaction=t.DbTrans;DbProviderFactorydbfactory=DbProviderFactories.GetFactory<DbHelper.dbProviderName>;DbDataAdapterdbDataAdapter=dbfactory.CreateDataAdapter<>;dbDataAdapter.SelectCommand=cmd;DataSetds=newDataSet<>;dbDataAdapter.Fill<ds>;returnds;}publicDataTableExecuteDataTable<DbCommandcmd,Transt>{cmd.Connection=t.DbConnection;cmd.Transaction=t.DbTrans;DbProviderFactorydbfactory=DbProviderFactories.GetFactory<DbHelper.dbProviderName>;DbDataAdapterdbDataAdapter=dbfactory.CreateDataAdapter<>;dbDataAdapter.SelectCommand=cmd;DataTabledataTable=newDataTable<>;dbDataAdapter.Fill<dataTable>;returndataTable;}publicDbDataReaderExecuteReader<DbCommandcmd,Transt>{cmd.Connection.Close<>;cmd.Connection=t.DbConnection;cmd.Transaction=t.DbTrans;DbDataReaderreader=cmd.ExecuteReader<>;DataTabledt=newDataTable<>;returnreader;}publicintExecuteNonQuery<DbCommandcmd,Transt>{cmd.Connection.Close<>;cmd.Connection=t.DbConnection;cmd.Transaction=t.DbTrans;intret=cmd.ExecuteNonQuery<>;returnret;}publicobjectExecuteScalar<DbCommandcmd,Transt>{cmd.Connection.Close<>;cmd.Connection=t.DbConnection;cmd.Transaction=t.DbTrans;objectret=cmd.ExecuteScalar<>;returnret;}#endregion}publicclassTrans:IDisposable{privateDbConnectionconn;privateDbTransactiondbTrans;publicDbConnectionDbConnection{get{returnthis.conn;}}publicDbTransactionDbTrans{get{returnthis.dbTrans;}}publicTrans<>{conn=DbHelper.CreateConnection<>;conn.Open<>;dbTrans=conn.BeginTransaction<>;}publicTrans<stringconnectionString>{conn=DbHelper.CreateConnection<connectionString>;conn.Open<>;dbTrans=conn.BeginTransaction<>;}publicvoidCommit<>{dbTrans.Commit<>;this.Colse<>;}publicvoidRollBack<>{dbTrans.Rollback<>;this.Colse<>;}publicvoidDispose<>{this.Colse<>;}publicvoidColse<>{if<conn.State==System.Data.ConnectionState.Open>{conn.Close<>;}}}那么如何使用它呢?下面我給出一些基本的使用示例,基本能滿足你大部分的數(shù)據(jù)庫操作需要了.

1>直接執(zhí)行sql語句DbHelperdb=newDbHelper<>;DbCommandcmd=db.GetSqlStringCommond<"insertt1<id>values<'haha'>">;db.ExecuteNonQuery<cmd>;2>執(zhí)行存儲過程DbHelperdb=newDbHelper<>;DbCommandcmd=db.GetStoredProcCommond<"t1_insert">;db.AddInParameter<cmd,"id",DbType.String,"heihei">;db.ExecuteNonQuery<cmd>;3>返回DataSetDbHelperdb=newDbHelper<>;DbCommandcmd=db.GetSqlStringCommond<"select*fromt1">;DataSetds=db.ExecuteDataSet<cmd>;4>返回DataTableDbHelperdb=newDbHelper<>;DbCommandcmd=db.GetSqlStringCommond<"t1_findall">;DataTabledt=db.ExecuteDataTable<cmd>;5>輸入?yún)?shù)/輸出參數(shù)/返回值的使用<比較重要哦>DbHelperdb=newDbHelper<>;DbCommandcmd=db.GetStoredProcCommond<"t2_insert">;db.AddInParameter<cmd,"timeticks",DbType.Int64,DateTime.Now.Ticks>;db.AddOutParameter<cmd,"outString",DbType.String,20>;db.AddReturnParameter<cmd,"returnValue",DbType.Int32>;db.ExecuteNonQuery<cmd>;strings=db.GetParameter<cmd,"outString">.Valueasstring;//outparameterintr=Convert.ToInt32<db.GetParameter<cmd,"returnValue">.Value>;//returnvalue6>DataReader使用DbHelperdb=newDbHelper<>;DbCommandcmd=db.GetStoredProcCommond<"t2_insert">;db.AddInParameter<cmd,"timeticks",DbType.Int64,DateTime.Now.Ticks>;db.AddOutParameter<cmd,"outString",DbType.String,20>;db.AddReturnParameter<cmd,"returnValue",DbType.Int32>;using<DbDataReaderreader=db.ExecuteReader<cmd>>{dt.Load<reader>;}strings=db.GetParameter<cmd,"outString">.Valueasstring;//outparameterintr=Convert.ToInt32<db.GetParameter<cmd,"returnValue">.Value>;//returnvalue7>事務(wù)的使用.<項(xiàng)目中需要將基本的數(shù)據(jù)庫操作組合成一個完整的業(yè)務(wù)流時,代碼級的事務(wù)是必不可少的哦>

pubicvoidDoBusiness<>{using<Transt=newTrans<>>{try{D1<t>;thrownewException<>;//如果有異常,會回滾滴D2<t>;t.Commit<>;}catch{t.RollBack<>;}}}publicvoidD1<Transt>{DbHelperdb=newDbHelper<>;DbCommandcmd=db.GetStoredProcCommond<"t2_insert">;db.AddInParameter<cmd,"timeticks",DbType.Int64,DateTime.Now.Ticks>;db.AddOutParameter<cmd,"outString",DbType.String,20>;db.AddReturnParameter<cmd,"returnValue",DbType.Int32>;if<t==null>db.ExecuteNonQuery<cmd>;elsedb.ExecuteNonQuery<cmd,t>;strings=db.GetParameter<cmd,"outString">.Valueasstring;//outparameterintr=Convert.ToInt32<db.GetParameter<cmd,"returnValue">.Value>;//returnvalue}publicvoidD2<Transt>{DbHelperdb=newDbHelper<>;DbCommandcmd=db.GetSqlStringCommond<"insertt1<id>values<'..'>">;if<t==null>db.ExecuteNonQuery<cmd>;elsedb.ExecuteNonQuery<cmd,t>;}

以上我們好像沒有指定數(shù)據(jù)庫連接字符串,大家如果看下DbHelper的代碼,就知道要使用它必須在config中配置兩個參數(shù),如下:<appSettings><addkey="DbHelperProvider"value="System.Data.SqlClient"/><addkey="DbHelperConnectionString"value="DataSource=<local>;InitialCatalog=DbHelperTest;PersistSecurityInfo=True;UserID=sa;Password=sa"/></appSettings>其實(shí),DbHelper需要的僅僅是兩個字符串,你可以自己修改,作成加密什么的...

好了,就這樣,DbHelper的代碼是非常簡單和透明的,只是在上做了一點(diǎn)小包裝,改變了一下使用它的程序員的編碼方式,去除掉一些比較"物理級"的編程概念,如connection的open和close之類的,使程序員更專注于業(yè)務(wù)邏輯代碼的編寫,少死掉點(diǎn)腦細(xì)胞,另外,統(tǒng)一了數(shù)據(jù)操作層的數(shù)據(jù)操作代碼的風(fēng)格和格式,維護(hù)起來很方便的撒~~~

另:以上代碼大家可以隨意使用,不需要給我費(fèi)的啦,嘿嘿.如果大家發(fā)現(xiàn)有什么BUG,或者有更好的數(shù)據(jù)操作類的實(shí)現(xiàn)方式,請聯(lián)系我哦..cnblogs./JemBai/archive/2008/09/02/1281864.程序中最常用的三十三種編程代碼標(biāo)簽.cnblogs./JemBai/archive/2008/09/02/1281964.html1.打開新的窗口并傳送參數(shù):傳送參數(shù):response.write<"<script>window.open<’*.aspx?id="+this.DropDownList1.SelectIndex+"&id1="+...+"’></script>">接收參數(shù):stringa=Request.QueryString<"id">;

stringb=Request.QueryString<"id1">;2.為按鈕添加對話框Button1.Attributes.Add<"onclick","returnconfirm<’確認(rèn)?’>">;

button.attributes.add<"onclick","if<confirm<’areyousure...?’>>{returntrue;}else{returnfalse;}">3.刪除表格選定記錄intintEmpID=<int>MyDataGrid.DataKeys[e.Item.ItemIndex];

stringdeleteCmd="DELETEfromEmployeewhereemp_id="+intEmpID.ToString<>4.刪除表格記錄警告privatevoidDataGrid_ItemCreated<Objectsender,DataGridItemEventArgse>

{

switch<e.Item.ItemType>

{

caseListItemType.Item:

caseListItemType.AlternatingItem:

caseListItemType.EditItem:

TableCellmyTableCell;

myTableCell=e.Item.Cells[14];

LinkButtonmyDeleteButton;

myDeleteButton=<LinkButton>myTableCell.Controls[0];

myDeleteButton.Attributes.Add<"onclick","returnconfirm<’您是否確定要刪除這條信息’>;">;

break;

default:

break;

}}5.點(diǎn)擊表格行另一頁privatevoidgrdCustomer_ItemDataBound<objectsender,System.Web.UI.WebControls.DataGridItemEventArgse>

{

//點(diǎn)擊表格打開

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>

{

stringOrderItemID=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>

{

stringOrderItemID=e.item.cells[1].Text;

...

e.item.Attributes.Add<"ondblclick","open<’../ShippedGrid.aspx?id="+OrderItemID+"’>">;

}★特別注意:[?id=]處不能為[?id=]6.表格超連接列傳遞參數(shù)<asp:HyperLinkColumnTarget="_blank"headertext="ID號"DataTextField="id"NavigateUrl="aaa.aspx?id=’

<%#DataBinder.Eval<Container.DataItem,"數(shù)據(jù)字段1">%>’&name=’<%#DataBinder.Eval<Container.DataItem,"數(shù)據(jù)字段2">%>’/>7.表格點(diǎn)擊改變顏色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里groundColor=’’;this.style.color=’’;">;

}

8.關(guān)于日期格式日期格式設(shè)定DataFormatString="{0:yyyy-MM-dd}"我覺得應(yīng)該在itembound事件中e.items.cell["你的列"].text=DateTime.Parse<e.items.cell["你的列"].text.ToString<"yyyy-MM-dd">>9.獲取錯誤信息并到指定頁面不要使用Response.Redirect,而應(yīng)該使用Server.Transfere.g//inglobal.asax

protectedvoidApplication_Error<Objectsender,EventArgse>{

if<Server.GetLastError<>isHttpUnhandledException>

Server.Transfer<"MyErrorPage.aspx">;//其余的非HttpUnhandledException異常交給ASP.NET自己處理就okay了:>

}Redirect會導(dǎo)致post-back的產(chǎn)生從而丟失了錯誤信息,所以頁面導(dǎo)向應(yīng)該直接在服務(wù)器端執(zhí)行,這樣就可以在錯誤處理頁面得到出錯信息并進(jìn)行相應(yīng)的處理10.清空CookieCookie.Expires=[DateTime];

Response.Cookies<"UserName">.Expires=0

11.自定義異常處理//自定義異常處理類

usingSystem;

usingSystem.Diagnostics;namespaceMyAppException

{

///<summary>

///從系統(tǒng)異常類ApplicationException繼承的應(yīng)用程序異常處理類。

///自動將異常容記錄到WindowsNT/2000的應(yīng)用程序日志

///</summary>

publicclassAppException:System.ApplicationException

{

publicAppException<>

{

if<ApplicationConfiguration.EventLogEnabled>LogEvent<"出現(xiàn)一個未知錯誤。">;

}publicAppException<stringmessage>

{

LogEvent<message>;

}publicAppException<stringmessage,ExceptioninnerException>

{

LogEvent<message>;

if<innerException!=null>

{

LogEvent<innerException.Message>;

}

}//日志記錄類

usingSystem;

usingSystem.Configuration;

usingSystem.Diagnostics;

usingSystem.IO;

usingSystem.Text;

usingSystem.Threading;namespaceMyEventLog

{

///<summary>

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

///<remarks>

///定義了4個日志記錄方法<error,warning,info,trace>

///</remarks>

///</summary>

publicclassApplicationLog

{

///<summary>

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

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

///</summary>

publicstaticvoidWriteError<Stringmessage>

{

WriteLog<TraceLevel.Error,message>;

}///<summary>

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

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

///</summary>

publicstaticvoidWriteWarning<Stringmessage>

{

WriteLog<TraceLevel.Warning,message>;

}///<summary>

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

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

///</summary>

publicstaticvoidWriteInfo<Stringmessage>

{

WriteLog<TraceLevel.Info,message>;

}

///<summary>

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

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

///</summary>

publicstaticvoidWriteTrace<Stringmessage>

{

WriteLog<TraceLevel.Verbose,message>;

}///<summary>

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

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

///<paramname="catchInfo">異常信息標(biāo)題字符串.</param>

///<retvalue>

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

///</retvalue>

///</summary>

publicstaticStringFormatException<Exceptionex,StringcatchInfo>

{

StringBuilderstrBuilder=newStringBuilder<>;

if<catchInfo!=String.Empty>

{

strBuilder.Append<catchInfo>.Append<"\r\n">;

}

strBuilder.Append<ex.Message>.Append<"\r\n">.Append<ex.StackTrace>;

returnstrBuilder.ToString<>;

}///<summary>

///實(shí)際事件日志寫入方法

///<paramname="level">要記錄信息的級別〔error,warning,info,trace>.</param>

///<paramname="messageText">要記錄的文本.</param>

///</summary>

privatestaticvoidWriteLog<TraceLevellevel,StringmessageText>

{

try

{

EventLogEntryTypeLogEntryType;

switch<level>

{

caseTraceLevel.Error:

LogEntryType=EventLogEntryType.Error;

break;

caseTraceLevel.Warning:

LogEntryType=EventLogEntryType.Warning;

break;

caseTraceLevel.Info:

LogEntryType=EventLogEntryType.Information;

break;

caseTraceLevel.Verbose:

LogEntryType=EventLogEntryType.SuccessAudit;

break;

default:

LogEntryType=EventLogEntryType.SuccessAudit;

break;

}EventLogeventLog=newEventLog<"Application",ApplicationConfiguration.EventLogMachineName,ApplicationConfiguration.EventLogSourceName>;

//寫入事件日志

eventLog.WriteEntry<messageText,LogEntryType>;}

catch{}//忽略任何異常

}

}//classApplicationLog

}12.Panel橫向滾動,縱向自動擴(kuò)展<asp:panelstyle="overflow-x:scroll;overflow-y:auto;"></asp:panel>13.回車轉(zhuǎn)換成Tab<scriptlanguage="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="xx/inc/delete.aspx?ID={0}"15.DataGrid行隨鼠標(biāo)變色privatevoidDGzf_ItemDataBound<objectsender,System.Web.UI.WebControls.DataGridItemEventArgse>

{

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:TEMPLATECOLUMNvisible="False"sortexpression="demo"headertext="ID">

<ITEMTEMPLATE>

<ASP:LABELtext=’<%#DataBinder.Eval<Container.DataItem,"ArticleID">%>’runat="server"width="80%"id="lblColumn"/>

</ITEMTEMPLATE>

</ASP:TEMPLATECOLUMN><ASP:TEMPLATECOLUMNheadertext="選中">

<HEADERSTYLEwrap="False"horizontalalign="Center"></HEADERSTYLE>

<ITEMTEMPLATE>

<ASP:CHECKBOXid="chkExport"runat="server"/>

</ITEMTEMPLATE>

<EDITITEMTEMPLATE>

<ASP:CHECKBOXid="chkExportON"runat="server"enabled="true"/>

</EDITITEMTEMPLATE>

</ASP:TEMPLATECOLUMN>后臺代碼protectedvoidCheckAll_CheckedChanged<objectsender,System.EventArgse>

{

//改變列的選定,實(shí)現(xiàn)全選或全不選。

CheckBoxchkExport;

if<CheckAll.Checked>

{

foreach<DataGridItemoDataGridIteminMyDataGrid.Items>

{

chkExport=<CheckBox>oDataGridItem.FindControl<"chkExport">;

chkExport.Checked=true;

}

}

else

{

foreach<DataGridItemoDataGridIteminMyDataGrid.Items>

{

chkExport=<CheckBox>oDataGridItem.FindControl<"chkExport">;

chkExport.Checked=false;

}

}

}17.數(shù)字格式化[<%#Container.DataItem<"price">%>的結(jié)果是500.0000,怎樣格式化為500.00?]<%#Container.DataItem<"price","{0:¥#,##0.00}">%>inti=123456;

strings=i.ToString<"###,###.00">;18.日期格式化[aspx頁面:<%#DataBinder.Eval<Container.DataItem,"Company_Ureg_Date">%>顯示為:2004-8-1119:44:28我只想要:2004-8-11]<%#DataBinder.Eval<Container.DataItem,"Company_Ureg_Date","{0:yyyy-M-d}">%>應(yīng)該如何改?[格式化日期]取出來,一般是object<<DateTime>objectFromDB>.ToString<"yyyy-MM-dd">;[日期的驗(yàn)證表達(dá)式]A.以下正確的輸入格式:[2004-2-29],[2004-02-2910:29:39pm],[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],[99990930],[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]>>$[大小寫轉(zhuǎn)換]HttpUtility.HtmlEncode<string>;

HttpUtility.HtmlDecode<string>19.如何設(shè)定全局變量Global.asax中Application_Start<>事件中添加Application[屬性名]=xxx;就是你的全局變量20.怎樣作到HyperLinkColumn生成的連接后,點(diǎn)擊連接,打開新窗口?HyperLinkColumn有個屬性Target,將器值設(shè)置成"_blank"即可.<Target="_blank">[ASPNETMENU]點(diǎn)擊菜單項(xiàng)彈出新窗口在你的menuData.xml文件的菜單項(xiàng)中加入URLTarget="_blank",如:<?xmlversion="1.0"encoding="GB2312"?>

<MenuDataImagesBaseURL="images/">

<MenuGroup>

<MenuItemLabel="參信息"URL="Infomation.aspx">

<MenuGroupID="BBC">

<MenuItemLabel="公告信息"URL="Infomation.aspx"URLTarget="_blank"LeftIcon="file.gif"/>

<MenuItemLabel="編制信息簡報"URL="NewInfo.aspx"LeftIcon="file.gif"/>

最好將你的aspnetmenu升級到1.2版21.讀取DataGrid控件TextBox值foreach<DataGriddgiinyourDataGrid.Items>

{

TextBoxtb=<TextBox>dgi.FindControl<"yourTextBoxId">;

tb.Text

}23.在DataGrid中有3個模板列包含Textbox分別為DG_ShuLiang<數(shù)量>DG_DanJian<單價>DG_JinE<金額>分別在5.6.7列,要求在錄入數(shù)量及單價的時候自動算出金額即:數(shù)量*單價=金額還要求錄入時限制為數(shù)值型.我如何用客戶端腳本實(shí)現(xiàn)這個功能?〖思?xì)w〗<asp:TemplateColumnHeaderText="數(shù)量">

<ItemTemplate>

<asp:TextBoxid="ShuLiang"runat=’server’Text=’<%#DataBinder.Eval<Container.DataItem,"DG_ShuLiang">%>’

onkeyup="javascript:DoCal<>"

/><asp:RegularExpressionValidatorid="revS"runat="server"ControlToValidate="ShuLiang"ErrorMessage="mustbeinteger"ValidationExpression="^\d+$"/>

</ItemTemplate>

</asp:TemplateColumn><asp:TemplateColumnHeaderText="單價">

<ItemTemplate>

<asp:TextBoxid="DanJian"runat=’server’Text=’<%#DataBinder.Eval<Container.DataItem,"DG_DanJian">%>’

onkeyup="javascript:DoCal<>"

/><asp:RegularExpressionValidatorid="revS2"runat="server"ControlToValidate="DanJian"ErrorMessage="mustbenumeric"ValidationExpression="^\d+<\.\d*>?$"/></ItemTemplate>

</asp:TemplateColumn><asp:TemplateColumnHeaderText="金額">

<ItemTemplate>

<asp:TextBoxid="JinE"runat=’server’Text=’<%#DataBinder.Eval<Container.DataItem,"DG_JinE">%>’/>

</ItemTemplate>

</asp:TemplateColumn><scriptlanguage="javascript">

functionDoCal<>

{

vare=event.srcElement;

varrow=e.parentNode.parentNode;

vartxts=row.all.tags<"INPUT">;

if<!txts.length||txts.length<3>

return;varq=txts[txts.length-3].value;

varp=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選定比較底下的行時,為什么總是刷新一下,然后就滾動到了最上面,剛才選定的行因屏幕的關(guān)系就看不到了。page_load

page.smartNavigation=true25.在Datagrid中修改數(shù)據(jù),當(dāng)點(diǎn)擊編輯鍵時,數(shù)據(jù)出現(xiàn)在文本框中,怎么控制文本框的大小?privatevoidDataGrid1_ItemDataBound<objsender,DataGridItemEventArgse>

{

for<inti=0;i<e.Item.Cells.Count-1;i++>

if<e.Item.ItemType==ListItemType.EditType>

{

e.Item.Cells[i].Attributes.Add<"Width","80px">

}

}26.對話框privatestaticstringScriptBegin="<scriptlanguage=\"JavaScript\">";

privatestaticstringScriptEnd="</script>";publicstaticvoidConfirmMessageBox<stringPageTarget,stringContent>

{

stringConfirmContent="varretValue=window.confirm<’"+Content+"’>;"+"if<retValue>{window.location=’"+PageTarget+"’;}";ConfirmContent=ScriptBegin+ConfirmContent+ScriptEnd;PageParameterPage=<Page>System.Web.HttpContext.Current.Handler;

ParameterPage.RegisterStartupScript<"confirm",ConfirmContent>;

//Response.Write<strScript>;

}27.將時間格式化:stringaa=DateTime.Now.ToString<"yyyy年MM月dd日">;1.1取當(dāng)前年月日時分秒currentTime=System.DateTime.Now;1.2取當(dāng)前年int年=DateTime.Now.Year;1.3取當(dāng)前月int月=DateTime.Now.Month;1.4取當(dāng)前日int日=DateTime.Now.Day;1.5取當(dāng)前時int時=DateTime.Now.Hour;1.6取當(dāng)前分int分=DateTime.Now.Minute;1.7取當(dāng)前秒int秒=DateTime.Now.Second;1.8取當(dāng)前毫秒int毫秒=DateTime.Now.Millisecond;

28.自定義分頁代碼:先定義變量:publicstaticintpageCount;//總頁面數(shù)

publicstaticintcurPageIndex=1;//當(dāng)前頁面下一頁:if<DataGrid1.CurrentPageIndex<<DataGrid1.PageCount-1>>

{

DataGrid1.CurrentPageIndex+=1;

curPageIndex+=1;

}bind<>;//DataGrid1數(shù)據(jù)綁定函數(shù)上一頁:if<DataGrid1.CurrentPageIndex>0>

{

DataGrid1.CurrentPageIndex+=1;

curPageIndex-=1;

}bind<>;//DataGrid1數(shù)據(jù)綁定函數(shù)直接頁面跳轉(zhuǎn):inta=int.Parse<JumpPage.Value.Trim<>>;//JumpPage.Value.Trim<>為跳轉(zhuǎn)值if<a<DataGrid1.PageCount>

{

this.DataGrid1.CurrentPageIndex=a;

}bind<>;29.DataGrid使用:添加刪除確認(rèn):privatevoidDataGrid1_ItemCreated<objectsender,System.Web.UI.WebControls.DataGridItemEventArgse>

{

foreach<DataGridItemdiinthis.DataGrid1.Items>

{

if<di.ItemType==ListItemType.Item||di.ItemType==ListItemType.AlternatingItem>

{

<<LinkButton>di.Cells[8].Controls[0]>.Attributes.Add<"onclick","returnconfirm<’確認(rèn)刪除此項(xiàng)嗎?’>;">;

}

}

}樣式交替:ListItemTypeitemType=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’;";

}

elseif<itemType==ListItemType.Al

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論