温故知新ASP.NET 2.0(C#)(8) - DataSourceControl(数据源控件)

简介:
[索引页]
[源码下载]



温故知新ASP.NET 2.0(C#)(8) - DataSourceControl(数据源控件)


作者: webabcd


介绍
在 ASP.NET 2.0 中有几个新的数据源控件,例如,SqlDataSource、ObjectDataSource、XmlDataSource、AccessDataSource 和 SiteMapDataSource。它们全都可以用来从它们各自类型的数据源中检索数据,并且可以绑定到各种数据绑定控件。数据源控件减少了为检索和绑定数据甚至对数据进行排序、分页或编辑而需要编写的自定义代码的数量。

其中 ObjectDataSource 控件可针对各种基础数据存储区(如 SQL 数据库或 XML)启用声明性数据绑定模型。因为页开发人员也常常将数据检索(也可能包含业务逻辑)封装在一个组件对象中,从而在呈现页和数据提供程序之间引入另一个层。ObjectDataSource 控件允许开发人员使用此传统的三层结构构造应用程序,同时仍然能够利用 ASP.NET 中的声明性数据绑定模型的易用性优点。


关键
1、在数据层创建 强类型的DataSet和TableAdapter,TableAdapter查询可以使用现有的存储过程。注:直接把表或存储过程拖进来会自动创建TableAdapter

2、中间层的类用[System.ComponentModel.DataObject]声明为数据组件,CRUD方法分别对应[DataObjectMethod(DataObjectMethodType.Insert)],[DataObjectMethod(DataObjectMethodType.Select)],[DataObjectMethod(DataObjectMethodType.Update)],[DataObjectMethod(DataObjectMethodType.Delete)] 

3、web层使用ObjectDataSource展现数据,ObjectDataSource就相当于一个代理。ObjectDataSource只是查找具有匹配的参数名称的方法,它不会使用参数的 Type 或 Size,而只是对参数的名称进行匹配

4、其它
  ·<asp:Parameter />有ConvertEmptyStringToNull属性,默认是true。另外还有Direction属性
  ·注意<asp:BoundField />的这几个属性NullDisplayText,HtmlEncode,ApplyFormatInEditMode,InsertVisible,DataFormatString,ReadOnly
  ·DataKeyNames有多个值的话用“,”分隔,用<asp:ControlParameter />绑定的话给其加一个“PropertyName”属性,值类似如下“SelectedDataKey.Values[0]”
  ·关于绑定:简单属性<%# custID %>;集合<asp:ListBox id="List1" datasource='<%# myArray %>' runat="server">;表达式<%# ( customer.FirstName + " " + customer.LastName ) %>;方法<%# GetBalance(custID) %> 
  ·<%# Eval("field1") %> 和 <%# Bind("field1") %>,Eval是单向绑定,Bind是双向邦定
  ·<asp:ObjectDataSource />有一个OldValuesParameterFormatString属性一般不用,不过如果要处理乐观并发之类的就会用到。当该属性的值为“original_{0}”的时候“original_参数名”则为初始值
  ·还有一些如编程方式给参数赋值,错误处理,得到返回值之类的请看源码


示例
相关存储过程和数据层略,见源码

单例模式的实现
App_Code/Singleton.cs
InBlock.gif using System; 
InBlock.gif using System.Data; 
InBlock.gif using System.Configuration; 
InBlock.gif using System.Web; 
InBlock.gif using System.Web.Security; 
InBlock.gif using System.Web.UI; 
InBlock.gif using System.Web.UI.WebControls; 
InBlock.gif using System.Web.UI.WebControls.WebParts; 
InBlock.gif using System.Web.UI.HtmlControls; 
InBlock.gif 
/// <summary> 
/// Singleton 的摘要说明 
/// </summary> 
InBlock.gif public  class Singleton<T> where T :  new() 
InBlock.gif
InBlock.gif         public  static T Instance 
InBlock.gif        { 
InBlock.gif                get {  return SingletonCreator.instance; } 
InBlock.gif        } 
InBlock.gif 
InBlock.gif         class SingletonCreator 
InBlock.gif        { 
InBlock.gif                 internal  static  readonly T instance =  new T(); 
InBlock.gif        } 
InBlock.gif}
 
中间层代码
App_Code/Test.cs
InBlock.gif using System; 
InBlock.gif using System.Data; 
InBlock.gif using System.Configuration; 
InBlock.gif using System.Web; 
InBlock.gif using System.Web.Security; 
InBlock.gif using System.Web.UI; 
InBlock.gif using System.Web.UI.WebControls; 
InBlock.gif using System.Web.UI.WebControls.WebParts; 
InBlock.gif using System.Web.UI.HtmlControls; 
InBlock.gif 
InBlock.gif using TestDatabaseTableAdapters; 
InBlock.gif using System.ComponentModel; 
InBlock.gif 
/// <summary> 
/// Test 的摘要说明 
/// </summary> 
InBlock.gif[DataObject] 
InBlock.gif public  class Test 
InBlock.gif
InBlock.gif        [DataObjectMethod(DataObjectMethodType.Select,  true)] 
InBlock.gif         public TestDatabase.TestDataTable GetTest() 
InBlock.gif        { 
InBlock.gif                 return Singleton<TestTableAdapter>.Instance.GetTest(); 
InBlock.gif        } 
InBlock.gif 
InBlock.gif        [DataObjectMethod(DataObjectMethodType.Select,  false)] 
InBlock.gif         public TestDatabase.TestDataTable GetTestById( int id) 
InBlock.gif        { 
InBlock.gif                 return Singleton<TestTableAdapter>.Instance.GetTestById(id); 
InBlock.gif        } 
InBlock.gif 
InBlock.gif        [DataObjectMethod(DataObjectMethodType.Insert,  true)] 
InBlock.gif         public  int?[] InsertTest( int? parentId,  string name, DateTime? publishTime,  decimal? price,  bool? isGood,  out  int? minId) 
InBlock.gif        { 
InBlock.gif                 // 仅为说明如何做错误处理 
InBlock.gif                 if (String.IsNullOrEmpty(name)) 
InBlock.gif                         throw  new ArgumentException( "参数不能是空""name"); 
InBlock.gif 
InBlock.gif                 int? id =  null
InBlock.gif                 int? count =  null
InBlock.gif                minId =  null
InBlock.gif 
InBlock.gif                Singleton<TestTableAdapter>.Instance.InsertTest(parentId, name, publishTime, price, isGood,  ref id,  refcount,  ref minId); 
InBlock.gif                 return  new  int?[] { id, count }; 
InBlock.gif        } 
InBlock.gif 
InBlock.gif        [DataObjectMethod(DataObjectMethodType.Delete,  true)] 
InBlock.gif         public  int? DeleteTest( int id) 
InBlock.gif        { 
InBlock.gif                 int? rowAffected; 
InBlock.gif 
InBlock.gif                rowAffected = Singleton<TestTableAdapter>.Instance.DeleteTest(id); 
InBlock.gif                 return rowAffected; 
InBlock.gif        } 
InBlock.gif 
InBlock.gif        [DataObjectMethod(DataObjectMethodType.Update,  true)] 
InBlock.gif         public  int? UpdateTest( int? id,  int? parentId,  string name, DateTime? publishTime,  decimal? price,  bool? isGood) 
InBlock.gif        { 
InBlock.gif                 int? rowAffected; 
InBlock.gif 
InBlock.gif                rowAffected = Singleton<TestTableAdapter>.Instance.UpdateTest(id, parentId, name, publishTime, price, isGood); 
InBlock.gif                 return rowAffected; 
InBlock.gif        } 
InBlock.gif}
 
DataSourceControl/Test.aspx
<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Test.aspx.cs" 
        Inherits="DataSourceControl_Test" Title="数据源控件测试" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"> 
        <p> 
                <asp:Label ID="lblMsg" runat="server" ForeColor="red" /> 
        </p> 
        <table cellpadding="6"> 
                <tr> 
                        <td valign="top"> 
                                <asp:DetailsView ID="DetailsView1" runat="server" AllowPaging="True" AutoGenerateRows="False" 
                                        DataKeyNames="Id" DataSourceID="ObjectDataSource1" Height="50px" Width="125px" OnItemInserted="DetailsView1_ItemInserted"> 
                                        <Fields> 
                                                <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" 
                                                        SortExpression="Id" /> 
                                                <asp:BoundField DataField="ParentId" HeaderText="ParentId" SortExpression="ParentId" /> 
                                                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" /> 
                                                <asp:BoundField DataField="PublishTime" HeaderText="PublishTime" SortExpression="PublishTime" 
                                                        InsertVisible="False" /> 
                                                <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" DataFormatString="{0:c}" HtmlEncode="False" /> 
                                                <asp:CheckBoxField DataField="IsGood" HeaderText="IsGood" SortExpression="IsGood" /> 
                                                <asp:CommandField ShowInsertButton="True" /> 
                                        </Fields> 
                                </asp:DetailsView> 
                        </td> 
                        <td valign="top"> 
                                <asp:DetailsView ID="DetailsView2" runat="server" Height="50px" Width="125px" AutoGenerateRows="False" DataKeyNames="Id" DataSourceID="ObjectDataSource2"> 
                                        <Fields> 
                                                <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" 
                                                        SortExpression="Id" /> 
                                                <asp:BoundField DataField="ParentId" HeaderText="ParentId" SortExpression="ParentId" /> 
                                                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" /> 
                                                <asp:BoundField DataField="PublishTime" HeaderText="PublishTime" SortExpression="PublishTime" /> 
                                                <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" DataFormatString="{0:c}" HtmlEncode="false" /> 
                                                <asp:CheckBoxField DataField="IsGood" HeaderText="IsGood" SortExpression="IsGood" /> 
                                        </Fields> 
                                </asp:DetailsView> 
                        </td> 
                </tr> 
        </table> 
        <p> 
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id" 
                        DataSourceID="ObjectDataSource1" AllowPaging="True" AllowSorting="True" OnRowUpdating="GridView1_RowUpdating"> 
                        <Columns> 
                                <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" /> 
                                <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" 
                                        SortExpression="Id" /> 
                                <asp:BoundField DataField="ParentId" HeaderText="ParentId" SortExpression="ParentId" 
                                        NullDisplayText="我的值是NULL" /> 
                                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" /> 
                                <asp:BoundField DataField="PublishTime" HeaderText="PublishTime" SortExpression="PublishTime" 
                                        ReadOnly="true" /> 
                                <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" DataFormatString="{0:c}" HtmlEncode="false" ApplyFormatInEditMode="True" /> 
                                <asp:CheckBoxField DataField="IsGood" HeaderText="IsGood" SortExpression="IsGood" /> 
                        </Columns> 
                </asp:GridView> 
        </p> 
        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetTest" 
                TypeName="Test" InsertMethod="InsertTest" DeleteMethod="DeleteTest" UpdateMethod="UpdateTest" 
                OnInserting="ObjectDataSource1_Inserting" OnInserted="ObjectDataSource1_Inserted"> 
                <InsertParameters> 
                        <%--ConvertEmptyStringToNull属性默认为true--%> 
                        <asp:Parameter Name="parentId" Type="Int32" ConvertEmptyStringToNull="true" /> 
                        <asp:Parameter Name="name" Type="String" /> 
                        <asp:Parameter Name="publishTime" Type="DateTime" /> 
                        <asp:Parameter Name="price" Type="Decimal" /> 
                        <asp:Parameter Name="isGood" Type="Boolean" /> 
                        <asp:Parameter Direction="Output" Name="minId" Type="Int32" /> 
                </InsertParameters> 
                <DeleteParameters> 
                        <asp:Parameter Name="id" Type="Int32" /> 
                </DeleteParameters> 
                <UpdateParameters> 
                        <asp:Parameter Name="id" Type="Int32" /> 
                        <asp:Parameter Name="parentId" Type="Int32" /> 
                        <asp:Parameter Name="name" Type="String" /> 
                        <asp:Parameter Name="publishTime" Type="DateTime" /> 
                        <asp:Parameter Name="price" Type="Decimal" /> 
                        <asp:Parameter Name="isGood" Type="Boolean" /> 
                </UpdateParameters> 
        </asp:ObjectDataSource> 
        <asp:ObjectDataSource ID="ObjectDataSource2" runat="server" OldValuesParameterFormatString="original_{0}" 
                SelectMethod="GetTestById" TypeName="Test"> 
                <SelectParameters> 
                        <asp:ControlParameter ControlID="GridView1" Name="id" PropertyName="SelectedValue" 
                                Type="Int32" /> 
                </SelectParameters> 
        </asp:ObjectDataSource> 
</asp:Content>
 
DataSourceControl/Test.aspx.cs
InBlock.gif using System; 
InBlock.gif using System.Data; 
InBlock.gif using System.Configuration; 
InBlock.gif using System.Collections; 
InBlock.gif using System.Web; 
InBlock.gif using System.Web.Security; 
InBlock.gif using System.Web.UI; 
InBlock.gif using System.Web.UI.WebControls; 
InBlock.gif using System.Web.UI.WebControls.WebParts; 
InBlock.gif using System.Web.UI.HtmlControls; 
InBlock.gif 
InBlock.gif public partial  class DataSourceControl_Test : System.Web.UI.Page 
InBlock.gif
InBlock.gif         protected  void Page_Load( object sender, EventArgs e) 
InBlock.gif        { 
InBlock.gif 
InBlock.gif        } 
InBlock.gif 
InBlock.gif         protected  void ObjectDataSource1_Inserting( object sender, ObjectDataSourceMethodEventArgs e) 
InBlock.gif        { 
InBlock.gif                 // 编程方式给参数赋值 
InBlock.gif                 if (e.InputParameters[ "publishTime"] ==  null
InBlock.gif                { 
InBlock.gif                        e.InputParameters[ "publishTime"] = DateTime.Now; 
InBlock.gif                } 
InBlock.gif        } 
InBlock.gif 
InBlock.gif         protected  void ObjectDataSource1_Inserted( object sender, ObjectDataSourceStatusEventArgs e) 
InBlock.gif        { 
InBlock.gif                 // 错误处理 
InBlock.gif                 if (e.Exception !=  null
InBlock.gif                { 
InBlock.gif                         if (e.Exception.InnerException !=  null
InBlock.gif                        { 
InBlock.gif                                Exception inner = e.Exception.InnerException; 
InBlock.gif 
InBlock.gif                                 if (inner  is ArgumentException) 
InBlock.gif                                { 
InBlock.gif                                         string paramName = ((ArgumentException)inner).ParamName; 
InBlock.gif                                        lblMsg.Text =  string.Concat( "参数 ", paramName,  " 有问题"); 
InBlock.gif                                } 
InBlock.gif                        } 
InBlock.gif                } 
InBlock.gif                 else 
InBlock.gif                { 
InBlock.gif                         int?[] ary = ( int?[])e.ReturnValue; 
InBlock.gif                        lblMsg.Text =  "新插入信息的ID是:" + ary[0].ToString(); 
InBlock.gif                        lblMsg.Text +=  "<br />数据总数是:" + ary[1].ToString(); 
InBlock.gif 
InBlock.gif                        lblMsg.Text +=  "<br />最小ID是:" + e.OutputParameters[ "minId"].ToString(); 
InBlock.gif                } 
InBlock.gif        } 
InBlock.gif 
InBlock.gif         protected  void DetailsView1_ItemInserted( object sender, DetailsViewInsertedEventArgs e) 
InBlock.gif        { 
InBlock.gif                 if (e.Exception !=  null
InBlock.gif                { 
InBlock.gif                         // 错误已处理 
InBlock.gif                        e.ExceptionHandled =  true
InBlock.gif                         // DetailsView保持插入状态 
InBlock.gif                        e.KeepInInsertMode =  true
InBlock.gif                } 
InBlock.gif        } 
InBlock.gif 
InBlock.gif         protected  void GridView1_RowUpdating( object sender, GridViewUpdateEventArgs e) 
InBlock.gif        { 
InBlock.gif                 // 价格格式转换为decimal格式 
InBlock.gif                 if (e.NewValues[ "Price"] !=  null
InBlock.gif                        e.NewValues[ "Price"] =  decimal.Parse(e.NewValues[ "Price"].ToString(), System.Globalization.NumberStyles.Currency); 
InBlock.gif        } 
InBlock.gif}
 
 



     本文转自webabcd 51CTO博客,原文链接:http://blog.51cto.com/webabcd/344889,如需转载请自行联系原作者


相关文章
|
1月前
|
开发框架 前端开发 .NET
LIMS(实验室)信息管理系统源码、有哪些应用领域?采用C# ASP.NET dotnet 3.5 开发的一套实验室信息系统源码
集成于VS 2019,EXT.NET前端和ASP.NET后端,搭配MSSQL 2018数据库。系统覆盖样品管理、数据分析、报表和项目管理等实验室全流程。应用广泛,包括生产质检(如石化、制药)、环保监测、试验研究等领域。随着技术发展,现代LIMS还融合了临床、电子实验室笔记本和SaaS等功能,以满足复杂多样的实验室管理需求。
36 3
LIMS(实验室)信息管理系统源码、有哪些应用领域?采用C# ASP.NET dotnet 3.5 开发的一套实验室信息系统源码
|
29天前
|
Java C# 数据安全/隐私保护
|
1月前
|
Cloud Native API C#
C#的现代化:.NET Core引领的技术革命
【6月更文挑战第9天】`.NET Core引领C#现代化,实现跨平台革命,提升性能并支持云原生应用。异步编程模型优化体验,统一API简化开发流程。C#应用场景扩展,开发效率提高,技术创新加速,预示其未来在技术领域将持续发挥关键作用。`
34 10
|
9天前
|
人工智能 开发框架 调度
C#/.NET这些实用的技巧和知识点你都知道吗?
C#/.NET这些实用的技巧和知识点你都知道吗?
|
1月前
|
存储 编解码 算法
C#.NET逃逸时间算法生成分形图像的毕业设计完成!晒晒功能
该文介绍了一个使用C#.NET Visual Studio 2008开发的程序,包含错误修复的Julia、Mandelbrot和优化过的Newton三种算法,生成色彩丰富的分形图像。作者改进了原始算法的效率,将内层循环的画点操作移至外部,提升性能。程序提供五种图形模式,支持放大缩小及颜色更新,并允许用户自定义画布大小以调整精度。还具备保存为高质JPG的功能。附有四张示例图片展示生成的分形效果。
415 3
|
15天前
|
索引
详细解读c#ListBox控件
详细解读c#ListBox控件
|
1月前
|
XML 开发框架 .NET
【.NET Core】常见C#代码约定
【.NET Core】常见C#代码约定
23 5
|
17天前
|
开发框架 .NET Nacos
使用 Nacos 在 C# (.NET Core) 应用程序中实现高效配置管理和服务发现
使用 Nacos 在 C# (.NET Core) 应用程序中实现高效配置管理和服务发现
40 0
|
1月前
|
前端开发 Java C#
GitHub突破5k Star!这件事情我坚持了3年,努力打造C#/.NET/.NET Core全面的学习、工作、面试指南知识库
GitHub突破5k Star!这件事情我坚持了3年,努力打造C#/.NET/.NET Core全面的学习、工作、面试指南知识库
|
18天前
|
存储 IDE C#
C#入门:在JetBrains Rider中创建.Net Framework控制台应用程序,输出“Hello, World!”
C#入门:在JetBrains Rider中创建.Net Framework控制台应用程序,输出“Hello, World!”
51 0