ASP.NET 2.0 绑定高级技巧
1.简单数据绑定定
<%# DataBinder.Eval(Container.DataItem, "Price") %>
<!--Equivalent ASP.NET 2.0 data binding expression -->
<%# Eval("Price") %>
<!--XML data binding -->
<%# XPath("Price") %>
SqlDataSource 一切支持SQL语句的数据源控件
AccessDataSource Access数据源控件
XmlDataSource XML数据源控件
ObjectDataSource 自行编写组件的数据源控件
SiteMapDataSource 页面导航控件的数据源控件
ConnectionString 连接数据库的连接字符串
SelectCommand 用于执行查询的命令
InsertCommand 用于执行插入的命令
UpdateCommand 用于执行更新的命令
DeleteCommand 用于执行删除的命令
DataSourceMode 指定数据源类型是DataSet 或DataReader( 默认值= DataSet)
ProviderName 指定供应商(默认值= SQL Server .NET provider)
EnableCaching 指定是否打开缓存(默认值= false)
CacheDuration 指定结果被缓存多少妙
CacheExpirationPolicy 指定缓存间隔是sliding 还是absolute
CacheKeyDependency 使缓存依赖于一个特定键值
SqlCacheDependency 使缓存依赖于一个特定数据库实体
SelectParameters 为查询命令指定参数
InsertParameters 为插入命令指定参数
UpdateParameters 为更新命令指定参数
DeleteParameters 为删除命令指定参数
FilterParameters 为过滤器命令指定参数
ControlParameter 指定一个源自于控件的参数
CookieParameter 指定一个源自于cookie的参数
FormParameter 指定一个源自于表单的参数
ProfileParameter 指定一个源自于profile的参数
QueryStringParameter 制定于一个来源于查询字符串的参数
Parameter 为数据源绑定一个参数
SessionParameter 指定一个源自于session的参数
ConnectionString="server=localhost;database=northwind;"
SelectCommand="select distinct country from customers order by country" />
<asp:SqlDataSourceID="Customers" RunAt="server"
ConnectionString="server=localhost;database=northwind;"
SelectCommand="select * from customers where country =@Country">
<SelectParameters>
<asp:ControlParameterName="Country" ControlID="MyDropDownList"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
<asp:DropDownListID=" MyDropDownList" DataSourceID="Countries"
DataTextField="country" AutoPostBack="true" RunAt="server" />
<asp:DataGridDataSourceID="Customers" RunAt="server" />
ConnectionString="server=localhost;database=northwind;"
SelectCommand="proc_GetCountries" />
<asp:SqlDataSourceID="Customers" RunAt="server"
ConnectionString="server=localhost;database=northwind;"
SelectCommand="proc_GetCustomers">
<SelectParameters>
<asp:ControlParameterName="Country" ControlID="MyDropDownList"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
<asp:DropDownListID="MyDropDownList" DataSourceID="Countries"
DataTextField="country" AutoPostBack="true" RunAt="server" />
<asp:DataGridDataSourceID="Customers" RunAt="server" />
CREATE PROCEDURE proc_GetCustomers
@Country nvarchar(32) AS
SELECT * FROM Customers
WHERE Country = @Country
GO
CREATE PROCEDURE proc_GetCustomers
CREATE PROCEDURE proc_GetCountriesAS
SELECT DISTINCT Country
FROM Customers
ORDER BY Country
GO
支持缓存与XSL 转换,只支持查询绑定,不支持更新
<asp:TreeViewID="MyTreeView" DataSourceID="Rates" RunAt="server" />
DataFile XML 数据文件的路径
TransformFile 含有XSL 风格定义的数据文件路径
EnableCaching 指定是否开启cache (默认值= false)
XPath XPath 表达式用来确认数据
CacheDuration 以秒为单位的时间间隔
CacheExpirationPolicy 指定时间间隔是sliding 还是absolute
CacheKeyDependency 创建缓存依存于某个键
从数据组件绑定数据,提供中间件的数据绑定,使数据访问和UI脱离,两种数据绑定方式
SelectMethod, InsertMethod, UpdateMethod,and DeleteMethod
可选择是否使用缓存,可选择是否使用参数
4.1 ODS 关键属性
名称 描述
InsertParameters 指定插入方法参数
UpdateParameters 指定更新方法参数
DeleteParameters 指定删除方法参数
SelectParameters 指定查询方法参数
CacheDuration 缓存间隔时间以秒为单位
SqlCacheDependency 基于某个数据实体的缓存
创建和清除
ObjectDataSource.SelectMethod 可以使用静态方法也可以使用一个类的新实例
如果使用实例方法:ODS 在每次调用的时候创建一个新实例类必须具有公共的建构函数
使用ObjectCreated 和ObjectDisposing 元素可以初始化和撤销函数
支持复杂的数据单元格类型,包括CheckBoxFields在<Columns> 元素中声明高可定制的用户界面
gridView 列类型:
BoundField 显示数据库中取出的文本
ButtonField 显示按钮
CheckBoxField 使用check boxes显示一个boolean型变量
HyperLinkField 显示一个超链接
TemplateField 显示一个自定义的HTML模板
CommandField 显示一个查询或者编辑按钮
ImageField 显示一个图片
如果数据在取出之后被改变,则修改失败
UpdateCommand结构构成指定ConflictDetection=“CompareAllValues”来实现
后入胜利
无论数据是否被修改,该修改都会成功
UpdateCommand结构构成指定ConflictDetection=“OverwriteChanges”来实现
ConnectionString="server=localhost;database=northwind;"
SelectCommand="select employeeid, lastname, firstnamefrom employees"
UpdateCommand="update employees set lastname=@lastname, firstname=
@firstnamewhere employeeid=@original_employeeid and lastname=
@original_lastnameand firstname=@original_firstname"
ConflictDetection="CompareAllValues">
<UpdateParameters>
<asp:ParameterName="EmployeeID" Type="Int32" />
<asp:ParameterName="lastname" Type="String" />
<asp:ParameterName="firstname" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:GridViewDataSourceID="Employees" Width="100%" RunAt="server"
DataKeyNames="EmployeeID" AutoGenerateEditButton="true" />
数据更新后控件调用的事件GridView.RowUpdated,DetailsView.ItemUpdated,SqlDataSource.Updated, etc.
处理“status”的事件,无论数据库是否异常允许数据库异常被处理或者再次抛弃,显示多少数据库行被修改
处理更新错误
UpdateCommand="" OnUpdated="OnUpdateComplete">
</asp:SqlDataSource>
void OnUpdateComplete (Object source, SqlDataSourceStatusEventsArgse)
{
if (e.Exception!= null) {
// Exception thrown. Set e.ExceptionHandledto true to prevent
// the SqlDataSourcefrom throwing an exception, or leave it set
// to false to allow SqlDataSourceto rethrowthe exception
}
else if (e.AffectedRows== 0) {
// No exception was thrown, but no records were updated,either.
// Might want to let the user know that the update failed
}
}
1.为按钮添加确认对话框 Button1.Attributes.Add("onclick","return confirm(’确认?’)"); 2.删除表格选定记录 //获得DataGrid主键 3.删除表格记录警告 private void DataGrid_ItemCreated(Object sender,DataGridItemEventArgs e) 4.点击表格行链接另一页 private void grdCustomer_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) 5.双击表格连接到另一页 在itemDataBound事件中 if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 6.双击表格打开新一页 if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 7.表格超连接列传递参数 <asp:HyperLinkColumn Target="_blank" headertext="ID号" DataTextField="id" NavigateUrl="aaa.aspx?id=’ 8.表格点击改变颜色 if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem) 9.在表格行中移动鼠标时改变颜色 写在DataGrid的_ItemDataBound里 if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem) 10.关于日期格式 日期格式设定 DataFormatString="{0:yyyy-MM-dd}" 我觉得应该在itembound事件中 e.items.cell["你的列"].text=DateTime.Parse(e.items.cell["你的列"].text.ToString("yyyy-MM-dd")) 11.获取错误信息并到指定页面 不要使用Response.Redirect,而应该使用Server.Transfer e.g // in global.asax //其余的非HttpUnhandledException异常交给ASP.NET自己处理就okay了 :) Redirect会导致post-back的产生从而丢失了错误信息,所以页面导向应该直接在服务器端执行,这样就可以在错误处理页面得到出错信息并进行相应的处理。 12.清空Cookie Cookie.Expires=[DateTime]; 13.自定义异常处理 //自定义异常处理类 namespace MyAppException public AppException(string message) public AppException(string message,Exception innerException) //日志记录类 namespace MyEventLog /// <summary> /// <summary> /// <summary> /// <summary> EventLog eventLog = new EventLog("Application", ApplicationConfiguration.EventLogMachineName, ApplicationConfiguration.EventLogSourceName ); } 14.Panel 横向滚动,纵向自动扩展 <asp:panel style="overflow-x:scroll;overflow-y:auto;"></asp:panel> 15.回车转换成Tab <script language="javascript" for="document" event="onkeydown"> onkeydown="if(event.keyCode==13) event.keyCode=9" 16.DataGrid超级连接列 DataNavigateUrlField="字段名" DataNavigateUrlFormatString=http://xx/inc/delete.aspx?ID={0} 17.DataGrid行随鼠标变色 private void DGzf_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) 18.模板列 <ASP:TEMPLATECOLUMN visible="False" sortexpression="demo" headertext="ID"> <ASP:TEMPLATECOLUMN headertext="选中"> 后台代码 protected void CheckAll_CheckedChanged(object sender, System.EventArgs e) 19.数字格式化 【<%#Container.DataItem("price")%>的结果是500.0000,怎样格式化为500.00?】 <%#Container.DataItem("price","{0:¥#,##0.00}")%> int i=123456; 20.日期格式化 【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})))?$ ^\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); 21.怎样作到HyperLinkColumn生成的连接后,点击连接,打开新窗口? HyperLinkColumn有个属性Target,将器值设置成"_blank"即可.(Target="_blank") 【ASPNETMENU】点击菜单项弹出新窗口 在你的menuData.xml文件的菜单项中加入URLTarget="_blank",如: <?xml version="1.0" encoding="GB2312"?> 22.读取DataGrid控件TextBox值 foreach(DataGrid dgi in yourDataGrid.Items) 23.在DataGrid中有3个模板列包含Textbox分别为 DG_ShuLiang (数量) DG_DanJian(单价) DG_JinE(金额)分别在5.6.7列,要求在录入数量及单价的时候自动算出金额即:数量*单价=金额还要求录入时限制为 数值型.我如何用客户端脚本实现这个功能? <asp:TemplateColumn HeaderText="数量"> <asp:RegularExpressionValidator id="revS" runat="server" ControlToValidate="ShuLiang" ErrorMessage="must be integer" ValidationExpression="^\d+$" /> <asp:TemplateColumn HeaderText="单价"> <asp:RegularExpressionValidator id="revS2" runat="server" ControlToValidate="DanJian" ErrorMessage="must be numeric" ValidationExpression="^\d+(\.\d*)?$" /> </ItemTemplate> <asp:TemplateColumn HeaderText="金额"> var q = txts[txts.length-3].value; if (isNaN(q) || isNaN(p)) q = parseInt(q); txts[txts.length-1].value = (q * p).toFixed(2); 24.datagrid选定比较底下的行时,为什么总是刷新一下,然后就滚动到了最上面,刚才选定的行因屏幕的关系就看不到了。 page_load 25.在Datagrid中修改数据,当点击编辑键时,数据出现在文本框中,怎么控制文本框的大小 ? private void DataGrid1_ItemDataBound(obj sender,DataGridItemEventArgs e) 26.对话框 private static string ScriptBegin = "<script language=\"JavaScript\">"; public static void ConfirmMessageBox(string PageTarget,string Content) ConfirmContent=ScriptBegin + ConfirmContent + ScriptEnd; Page ParameterPage = (Page)System.Web.HttpContext.Current.Handler; 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; //总页面数 下一页: if(DataGrid1.CurrentPageIndex < (DataGrid1.PageCount - 1)) bind(); // DataGrid1数据绑定函数 上一页: if(DataGrid1.CurrentPageIndex >0) bind(); // DataGrid1数据绑定函数 直接页面跳转: int a=int.Parse(JumpPage.Value.Trim());//JumpPage.Value.Trim()为跳转值 if(a<DataGrid1.PageCount) bind(); 29.DataGrid添加删除确认: private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) 30.DataGrid样式交替: ListItemType itemType = e.Item.ItemType; if (itemType == ListItemType.Item ) 31.DataGrid添添加一个编号列: DataTable dt= c.ExecuteRtnTableForAccess(sqltxt); //执行sql返回的DataTable for(int i=0;i<dt.Rows.Count;i++) DataGrid1.DataSource=dt; 32.DataGrid1中添加一个CheckBox,页面中添加一个全选框 private void CheckBox2_CheckedChanged(object sender, System.EventArgs e) 33.DataGrid添将当前页面中DataGrid1显示的数据全部删除 foreach(DataGridItem thisitem in DataGrid1.Items) 34.当文件在不同目录下,需要获取数据库连接字符串(如果连接字符串放在Web.config,然后在Global.asax中初始化) 在Application_Start中添加以下代码: Application["ConnStr"]=this.Context.Request.PhysicalApplicationPath+ConfigurationSettings. 35.变量.ToString() 字符型转换 转为字符串 12345.ToString("n"); //生成 12,345.00 36.在自己的网站上登陆其他网站:(如果你的页面是通过嵌套方式的话,因为一个页面只能有一个FORM,这时可以导向另外一个页面再提交登陆信息) <SCRIPT language="javascript"> </SCRIPT> <body leftMargin="0" topMargin="0" onload=" gook()" marginwidth="0" marginheight="0"> 文本框的名称必须是你要登陆的网页上的名称,如果源码不行可以用vsniffer 看看。 下面是获取用户输入的登陆信息的代码: string name; try |
在asp.net 2.0中,可以强制对viewstate进行分段传输了,使用的是Page.MaxPageStateFieldLength 属性,可以设置viewstate中,每个页面状态字段的最大字节数。格式如下,要在WEB.CONFIG文件里设置的:
<pages maxPageStateFieldLength="5" />
其中,将设置把viewstate为不超过5字节,如果实际的viewstate超过该值,将进行分段传输,但每个分段的大小依然不超过maxPageStateFieldLength中的设置值, 默认设置值为-1,表示不对其进行分段传输。
2.Click button only once in asp.net 2.0
1 protected void Page_Load(object sender, EventArgs e)
2 {
3 PostBackOptions options = new PostBackOptions(Button1,string.Empty);
4
5 StringBuilder sb = new StringBuilder();
6 if (Button1.CausesValidation && this.GetValidators(Button1.ValidationGroup).Count > 0)
7 {
8 options.ClientSubmit = true;
9 options.PerformValidation = true;
10 options.ValidationGroup = Button1.ValidationGroup;
11
12 sb.Append("if (typeof(Page_ClientValidate) == 'function')");
13 sb.Append("if(Page_ClientValidate(\"" + Button1.ValidationGroup + "\")==false) return false;");
14 }
15 if (!string.IsNullOrEmpty(Button1.PostBackUrl))
16 options.ActionUrl = HttpUtility.UrlPathEncode(Button1.ResolveClientUrl(Button1.PostBackUrl));
17
18 sb.Append("this.disabled = true;");
19 sb.Append(ClientScript.GetPostBackEventReference(options));
20 sb.Append(";");
21 Button1.Attributes.Add("onclick", sb.ToString());
22 }
3.asp.net 2.0中得到sqldatasource返回的行数
在asp.net 2.0中,gridview是和sqldatasource控件绑定的,那么如何得到sqldatasource返回的记录的行数呢?比如sqldatasource控件中用select * from ....,如何返回其记录行数?在.net 2.0中,可以通过sqldatasource的OnSelected事件实现,并且对select事件SqlDataSourceStatusEventArgs参数中的AffectedRows属性设置一下就可以了,具体核心代码如下:
protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
totalRows.Text = e.AffectedRows.ToString();
}
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=(local);Initial Catalog=Northwind;user id=sa;password=123456;" ProviderName="System.Data.SqlClient" SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName] FROM [Customers]" OnSelected="SqlDataSource1_Selected"></asp:SqlDataSource>
4.在asp.net 1.1中,当要在page_load页面中,设置某个控件为默认的焦点按钮(也就是默认焦点是在这个控件上的),可能要用到javascript的代码,而在ASP.NET 2.0中,不用这些麻烦了,在form代码中,使用
defaultbutton和 defaultfocus属性就可以了,比如
<form id="Form1"
defaultbutton="BtnSubmit"
defaultfocus="TextBox1"
runat="server">
则在页面加载时,默认的button按钮时btnsubmit,焦点默认就在texbox1上了
5.asp.net 2.0中的弹出对话框
在asp.net 1.1中,要做1个弹出的对话框的话,一般是在服务端的代码中这样写:
btnClick.Attributes.Add("onclick", "return confirm('Are you sure?');");
现在在ASP.NET 2.0中,只要使用客户端的代码就可以拉,新多了个onclientclick,这样写
<asp:button id="btnClick" runat="server" OnClientClick="return confirm('Are you sure?');" text="Button"></asp:button>
5.自定义的页面控件,
比如在ASP。NET 1。1中,要声明自定义的页面控件,
通常要在用到的每页都要加入register prefix=........这样的,很麻烦,而在asp.net 2.0中,如果你确定一个页面自定义控件要在
整个项目中用到,只需要在WEB.CONFIG中加入
<system.web>
<pages>
<controls>
<add tagPrefix="prefixname" namespace="namespacename "/>
</controls>
</pages>
</system.web>
其中prefixname为控件的标识,namespace为命名空间就可以了。
<controls>
<add tagPrefix="prefixname" namespace="namespacename "/>
</controls>
</pages>
</system.web>
其中prefixname为控件的标识,namespace为命名空间就可以了。
<controls>
<add tagPrefix="prefixname" namespace="namespacename "/>
</controls>
</pages>
</system.web>
其中prefixname为控件的标识,namespace为命名空间就可以了。
<controls>
<add tagPrefix="prefixname" namespace="namespacename "/>
</controls>
</pages>
</system.web>
其中prefixname为控件的标识,namespace为命名空间就可以了。