ObjectDataSource&&Gridview

ASP.NET 1.x 中DataGrid的功能在ASP.NET 2.0中得到了增强。DataGrid增强的功能在2.0中分散到了GridView、DetailsView 和FormView 三个控件中。今天讨论一下GridView与DetailsView如何联合使用。
 
GridView和DetailsView的用法与1.x中有很大的不同,主要是2.0新增了4个DataSource控件。其中有3个直接或间接继承自System.Web.UI.DataSourceControl 另一个(SiteMapDataSource)继承自System.Web.UI.HierarchicalDataSourceControl。在实际应用中,用的较多的是ObjectDataSource。ObjectDataSource控件支持Web开发的三层架构,把表示层和数据层真正分开了。
 
ObjectDataSource允许指定一个类给它的TypeName属性。同时指定这个类的一个公共方法给它的SelectMethod属性。这可以是一个中间层的类,在这个类中可以调用数据层的方法也可以与数据层完全无关。与ObjectDataSource相连的GridView或DetailsView则只负责显示,而与数据逻辑无关。
 
要在GridView中显示数据只要把一个ObjectDataSource的ID赋给GridView的DataSourceID属性(实际上GridView中绑定的数据源只需要实现IEnumerable 或 ItypedList接口即可)。
ObjectDataSource&&Gridview
在GridView的Smart Tag中有Choose Data Source的选项,可以选取页面中已存在的DataSource。选定DataSource后可以点击Configure Data Source,会出现下面的界面
ObjectDataSource&&Gridview在其中可以选择一个类,这个类的类名将会作为ObjectDataSource的TypeName属性。然后Next下去…
ObjectDataSource&&Gridview在这可以选择select、update、insert和delete分别对应的方法。但可以不选。一个ObjectDataSource的select方法是必须要有的,如果没有在这个界面中选择的话,可以在Page_Load方法中根据需要指定,例如(这个小示例与下面的例子无关):
 
 1 ObjectDataSource&&Gridview     void  Page_Load( object  sender, EventArgs e)
 2 ObjectDataSource&&Gridview     {
 3ObjectDataSource&&Gridview        if (!Page.IsPostBack)
 4ObjectDataSource&&Gridview        {
 5ObjectDataSource&&Gridview            if (Page.User.IsInRole("Administrator"))
 6ObjectDataSource&&Gridview            {
 7ObjectDataSource&&Gridview                ObjectDataSource1.SortParameterName = "sortParameter";
 8ObjectDataSource&&Gridview                ObjectDataSource1.SelectMethod = "GetStudents";
 9ObjectDataSource&&Gridview            }

10ObjectDataSource&&Gridview            else
11ObjectDataSource&&Gridview            {
12ObjectDataSource&&Gridview                ObjectDataSource1.SelectParameters.Add(new Parameter("Name", TypeCode.Int32, Page.User.Identity.Name));
13ObjectDataSource&&Gridview                ObjectDataSource1.SortParameterName = "sortParameter";
14ObjectDataSource&&Gridview                ObjectDataSource1.SelectMethod = "SelectStudent";
15ObjectDataSource&&Gridview            }

16ObjectDataSource&&Gridview        }

17ObjectDataSource&&Gridview}
 
对于GridView的数据显示,一个常见的问题是:它根据什么生成行,又根据什么生成列呢?GridView需要的数据源只需实现IEnumerable 或 ItypedList接口。所以ObjectDataSource的select方法的返回值也必然要遵守几个条件:实现IEnumerable 或 ItypedList接口或直接是DataSet。如果返回值是DataSet,GridView会根据DataSet中的第一个Table生成行和列。否则,将枚举每一个返回值作为一行,并根据返回值的类型应用反射技术找出它的public属性作为列(前提是AltoGenerateColumn属性设为true)。例如:select方法返回类型是List<StrudentData>
StudentData类型有Name, Age, ID, Sex等属性,那么GridView就会将返回的每一个StudentData作为一行,并生成相应的Name, Age, ID, Sex列。
 
DetailsView如果想要显示GridView当中选定行的详细信息,则需要新建一个ObjectDataSource,这个ObjectDataSource的TypeName一般与第一个ObjectDataSource的TypeName相同,但是它的select方法应该与第一个ObjectDataSource的不同。不同之处在于这个select方法应该接收一个参数(一般应该是返回类型的主键),用以确定显示哪个实例的具体信息。
ObjectDataSource&&Gridview
在接下来的Wizard中
ObjectDataSource&&Gridview要选取这个参数的数据源。注意右边的Parameter source,这里选择的是Control,表示是从页面的控件中读取数据。这个选项中还有Cookie,Form,Session等,分别代表不同的数据源。选择Control后,下面变成了ControlID的选择,这里选择了GridView1,就是要与之相连的GridView。注意左边的Parameters框,i的Value变成了GridView1.SelectValue。但仅仅这样的话,i是得不到值的。这里必须提到DataKeyName属性,这个属性代表GridView中数据的主键, 在这里GridView1的DataKeyName属性不能为空。也就是说,GridView的SelectValue属性实际上是选中行的名为DataKeyName的属性的值。即:如果GridView1的DataKeyName属性为”ID”,它所显示的数据列有一列为“ID”,则给i赋的值就是ID列的值。
 
在DetailsView中如果主键列不显示,也必须把主键列的列名赋值给DataKeyName属性(多个主键可以用逗号分开)。因为ViewState中只存放所显示列的值和在DataKeyName中指定的列的值。如果不赋值给DataKeyName的话,在DetailsView中使用Update、Delete方法的时候,主键列从ViewState中读取不到值,将会用默认值代替,这样就得不到想要的结果。
 
最后,介绍一下ObjectDataSource的DataObjectTypeName属性。我们在Update和Insert的时候往往需要多个参数代表对象的不同属性。这种做法首先容易出错,其次也不利于数据的封装。于是ObjectDataSource添加了一个DataObjectTypeName属性,这个属性确定了一个类,这个类可以封装要被修改或插入的值的全部属性值。在确定了这个属性后,在Update和Insert的函数中就可以用DataObjectTypeName属性定义的那个类作为参数类型。DataObjectTypeName的这种用法在下面的例子中可以看到。在调用在Update和Insert的时候,ASP.NET会自动实例化一个DataObjectTypeName属性定义的类型,并给它赋值,然后传给调用的函数。
 
做为DataObjectTypeName属性的类主要有以下三点要求:
1.       这个类必须有一个缺省的构造函数(就是0参数的构造函数)
2.       这个类的公有属性名必须和GridView或DetailsView所绑定的类的公有属性名相同
3.       这些公有属性必须get和set两种方法都具备。
 
经过上面的配置,GridView和DetailsView就可以配合使用了。下面是一个例子:
页面文件:
ObjectDataSource&&Gridview <% @ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"  %>
ObjectDataSource&&Gridview
ObjectDataSource&&Gridview
<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd" >
ObjectDataSource&&Gridview
< html  xmlns ="http://www.w3.org/1999/xhtml" >
ObjectDataSource&&Gridview
< head  runat ="server" >
ObjectDataSource&&Gridview    
< title > Untitled Page </ title >
ObjectDataSource&&Gridview
</ head >
ObjectDataSource&&Gridview
< body >
ObjectDataSource&&Gridview    
< form  id ="form1"  runat ="server" >
ObjectDataSource&&Gridview        
< asp:ObjectDataSource  ID ="ObjectDataSource1"  runat ="server"  InsertMethod ="InsertStudent"  SelectMethod ="GetStudents"  TypeName ="Student"  UpdateMethod ="UpdateStudent"  OldValuesParameterFormatString ="Original_{0}"  DataObjectTypeName ="StudentData"  DeleteMethod ="DeleteStudent" >
ObjectDataSource&&Gridview        
</ asp:ObjectDataSource >
ObjectDataSource&&Gridview        
< div >
ObjectDataSource&&Gridview            
< asp:GridView  ID ="GridView1"  runat ="server"  AllowSorting ="True"  CellPadding ="4"  DataSourceID ="ObjectDataSource1"  ForeColor ="#333333"  GridLines ="None"  DataKeyNames ="ID"  AutoGenerateColumns ="False" >
ObjectDataSource&&Gridview                
< FooterStyle  BackColor ="#507CD1"  Font-Bold ="True"  ForeColor ="White"   />
ObjectDataSource&&Gridview                
< RowStyle  BackColor ="#EFF3FB"   />
ObjectDataSource&&Gridview                
< Columns >
ObjectDataSource&&Gridview                    
< asp:CommandField  ShowSelectButton ="True"   />
ObjectDataSource&&Gridview                    
< asp:BoundField  DataField ="Name"  HeaderText ="Name"  SortExpression ="Name"   />
ObjectDataSource&&Gridview                
</ Columns >
ObjectDataSource&&Gridview                
< PagerStyle  BackColor ="#2461BF"  ForeColor ="White"  HorizontalAlign ="Center"   />
ObjectDataSource&&Gridview                
< SelectedRowStyle  BackColor ="#D1DDF1"  Font-Bold ="True"  ForeColor ="#333333"   />
ObjectDataSource&&Gridview                
< HeaderStyle  BackColor ="#507CD1"  Font-Bold ="True"  ForeColor ="White"   />
ObjectDataSource&&Gridview                
< EditRowStyle  BackColor ="#2461BF"   />
ObjectDataSource&&Gridview                
< AlternatingRowStyle  BackColor ="White"   />
ObjectDataSource&&Gridview            
</ asp:GridView >
ObjectDataSource&&Gridview            
&nbsp;   &nbsp;
ObjectDataSource&&Gridview            
< asp:ObjectDataSource  ID ="ObjectDataSource2"  runat ="server"  DataObjectTypeName ="StudentData"
ObjectDataSource&&Gridview                DeleteMethod
="DeleteStudent"  InsertMethod ="InsertStudent"  SelectMethod ="SelectStudent"
ObjectDataSource&&Gridview                TypeName
="Student"  UpdateMethod ="UpdateStudent" >
ObjectDataSource&&Gridview                
< SelectParameters >
ObjectDataSource&&Gridview                    
< asp:ControlParameter  ControlID ="GridView1"  Name ="i"  PropertyName ="SelectedValue"
ObjectDataSource&&Gridview                        Type
="Int32"   />
ObjectDataSource&&Gridview                
</ SelectParameters >
ObjectDataSource&&Gridview            
</ asp:ObjectDataSource >
ObjectDataSource&&Gridview            
&nbsp;&nbsp;
ObjectDataSource&&Gridview        
</ div >
ObjectDataSource&&Gridview        
< asp:DetailsView  ID ="DetailsView1"  runat ="server"  Height ="50px"  Width ="125px"  CellPadding ="8"  DataSourceID ="ObjectDataSource2"  ForeColor ="#333333"  GridLines ="None"  AutoGenerateRows ="False"  Font-Names ="宋体"  Font-Overline ="False"  Font-Size ="10pt"  Font-Strikeout ="False"  Font-Underline ="False"  DataKeyNames ="ID" >
ObjectDataSource&&Gridview            
< FooterStyle  BackColor ="#507CD1"  Font-Bold ="True"  ForeColor ="White"   />
ObjectDataSource&&Gridview            
< CommandRowStyle  BackColor ="#D1DDF1"  Font-Bold ="True"   />
ObjectDataSource&&Gridview            
< RowStyle  BackColor ="#EFF3FB"   />
ObjectDataSource&&Gridview            
< FieldHeaderStyle  BackColor ="#DEE8F5"  Font-Bold ="True"   />
ObjectDataSource&&Gridview            
< PagerStyle  BackColor ="#2461BF"  ForeColor ="White"  HorizontalAlign ="Left"   />
ObjectDataSource&&Gridview            
< Fields >
ObjectDataSource&&Gridview                
< asp:BoundField  DataField ="Age"  HeaderText ="Age"  SortExpression ="Age"   />
ObjectDataSource&&Gridview                
< asp:BoundField  DataField ="Name"  HeaderText ="Name"  SortExpression ="Name"   />
ObjectDataSource&&Gridview                
< asp:CheckBoxField  DataField ="Sex"  HeaderText ="Sex"  SortExpression ="Sex"   />
ObjectDataSource&&Gridview                
< asp:CommandField  ShowDeleteButton ="True"  ShowEditButton ="True"  ShowInsertButton ="True"   />
ObjectDataSource&&Gridview            
</ Fields >
ObjectDataSource&&Gridview            
< HeaderStyle  BackColor ="#507CD1"  Font-Bold ="True"  ForeColor ="White"   />
ObjectDataSource&&Gridview            
< EditRowStyle  BackColor ="#2461BF"   />
ObjectDataSource&&Gridview            
< AlternatingRowStyle  BackColor ="White"   />
ObjectDataSource&&Gridview        
</ asp:DetailsView >
ObjectDataSource&&Gridview    
</ form >
ObjectDataSource&&Gridview
</ body >
ObjectDataSource&&Gridview
</ html >
ObjectDataSource&&Gridview
后台代码:
Default.aspx.cs
ObjectDataSource&&Gridview using  System;
ObjectDataSource&&Gridview
using  System.Data;
ObjectDataSource&&Gridview
using  System.Configuration;
ObjectDataSource&&Gridview
using  System.Web;
ObjectDataSource&&Gridview
using  System.Web.Security;
ObjectDataSource&&Gridview
using  System.Web.UI;
ObjectDataSource&&Gridview
using  System.Web.UI.WebControls;
ObjectDataSource&&Gridview
using  System.Web.UI.WebControls.WebParts;
ObjectDataSource&&Gridview
using  System.Web.UI.HtmlControls;
ObjectDataSource&&Gridview
ObjectDataSource&&Gridview
public  partial  class  _Default : System.Web.UI.Page 
ObjectDataSource&&Gridview
{
ObjectDataSource&&Gridview    
protected void Page_Load(object sender, EventArgs e)
ObjectDataSource&&Gridview    
{
ObjectDataSource&&Gridview        DetailsView1.ItemCreated 
+= delegate(object s, EventArgs ee)
ObjectDataSource&&Gridview        
{
ObjectDataSource&&Gridview            GridView1.DataBind();
ObjectDataSource&&Gridview        }
;
ObjectDataSource&&Gridview
ObjectDataSource&&Gridview        DetailsView1.ItemDeleted 
+= delegate(object s, DetailsViewDeletedEventArgs ee)
ObjectDataSource&&Gridview        
{
ObjectDataSource&&Gridview            GridView1.DataBind();
ObjectDataSource&&Gridview        }
;
ObjectDataSource&&Gridview
ObjectDataSource&&Gridview        DetailsView1.ItemUpdated 
+= delegate(object s, DetailsViewUpdatedEventArgs ee)
ObjectDataSource&&Gridview        
{
ObjectDataSource&&Gridview            GridView1.DataBind();
ObjectDataSource&&Gridview        }
;
ObjectDataSource&&Gridview    }

ObjectDataSource&&Gridview
ObjectDataSource&&Gridview}

ObjectDataSource&&Gridview
App_Code/Students.cs
ObjectDataSource&&Gridview using  System;
ObjectDataSource&&Gridview
using  System.Data;
ObjectDataSource&&Gridview
using  System.Configuration;
ObjectDataSource&&Gridview
using  System.Web;
ObjectDataSource&&Gridview
using  System.Collections.Generic;
ObjectDataSource&&Gridview
using  System.Web.Security;
ObjectDataSource&&Gridview
using  System.Web.UI;
ObjectDataSource&&Gridview
using  System.Web.UI.WebControls;
ObjectDataSource&&Gridview
using  System.Web.UI.WebControls.WebParts;
ObjectDataSource&&Gridview
using  System.Web.UI.HtmlControls;
ObjectDataSource&&Gridview
ObjectDataSource&&Gridview
public   class  Student
ObjectDataSource&&Gridview
{
ObjectDataSource&&Gridview    
static private List<StudentData> students;
ObjectDataSource&&Gridview
ObjectDataSource&&Gridview    
public Student()
ObjectDataSource&&Gridview    
{
ObjectDataSource&&Gridview        
if (students == null)
ObjectDataSource&&Gridview        
{
ObjectDataSource&&Gridview            students 
= new List<StudentData>();
ObjectDataSource&&Gridview            StudentData data 
= new StudentData("Chiewen Ly"23true);
ObjectDataSource&&Gridview            students.Add(data);
ObjectDataSource&&Gridview
ObjectDataSource&&Gridview            data 
= new StudentData("A~ Foo"24false);
ObjectDataSource&&Gridview            students.Add(data);
ObjectDataSource&&Gridview
ObjectDataSource&&Gridview            data 
= new StudentData("lyg"25true);
ObjectDataSource&&Gridview            students.Add(data);
ObjectDataSource&&Gridview
ObjectDataSource&&Gridview        }

ObjectDataSource&&Gridview    }

ObjectDataSource&&Gridview
ObjectDataSource&&Gridview    
public List<StudentData> GetStudents()
ObjectDataSource&&Gridview    
{
ObjectDataSource&&Gridview        
return students;
ObjectDataSource&&Gridview    }

ObjectDataSource&&Gridview
ObjectDataSource&&Gridview    
public StudentData SelectStudent(int i)
ObjectDataSource&&Gridview    
{
ObjectDataSource&&Gridview        
foreach (StudentData student in students)
ObjectDataSource&&Gridview        
{
ObjectDataSource&&Gridview            
if (student.ID == i)
ObjectDataSource&&Gridview            
{
ObjectDataSource&&Gridview                
return student;
ObjectDataSource&&Gridview            }

ObjectDataSource&&Gridview        }

ObjectDataSource&&Gridview        
//如果返回一个null,则所绑定的控件将不会显示
ObjectDataSource&&Gridview
        return null;
ObjectDataSource&&Gridview    }

ObjectDataSource&&Gridview
ObjectDataSource&&Gridview    
public void InsertStudent(StudentData stuData)
ObjectDataSource&&Gridview    
{
ObjectDataSource&&Gridview        students.Add(stuData);
ObjectDataSource&&Gridview    }

ObjectDataSource&&Gridview
ObjectDataSource&&Gridview    
public void UpdateStudent(StudentData stuData)
ObjectDataSource&&Gridview    
{
ObjectDataSource&&Gridview        
foreach (StudentData student in students)
ObjectDataSource&&Gridview        
{
ObjectDataSource&&Gridview            
if (student.ID == stuData.ID)
ObjectDataSource&&Gridview            
{
ObjectDataSource&&Gridview                student.Name 
= stuData.Name;
ObjectDataSource&&Gridview                student.Age 
= stuData.Age;
ObjectDataSource&&Gridview                student.Sex 
= stuData.Sex;
ObjectDataSource&&Gridview            }

ObjectDataSource&&Gridview        }

ObjectDataSource&&Gridview    }

ObjectDataSource&&Gridview
ObjectDataSource&&Gridview    
public void DeleteStudent(StudentData stuData)
ObjectDataSource&&Gridview    
{
ObjectDataSource&&Gridview        StudentData theStudent 
= new StudentData();
ObjectDataSource&&Gridview        
foreach (StudentData student in students)
ObjectDataSource&&Gridview        
{
ObjectDataSource&&Gridview            
if (student.ID == stuData.ID)
ObjectDataSource&&Gridview            
{
ObjectDataSource&&Gridview                theStudent 
= student;
ObjectDataSource&&Gridview            }

ObjectDataSource&&Gridview        }

ObjectDataSource&&Gridview        students.Remove(theStudent);
ObjectDataSource&&Gridview    }

ObjectDataSource&&Gridview}

ObjectDataSource&&Gridview
ObjectDataSource&&Gridview
public   class  StudentData
ObjectDataSource&&Gridview
{
ObjectDataSource&&Gridview    
static private int IDseed = 1;
ObjectDataSource&&Gridview    
private string name;
ObjectDataSource&&Gridview    
private int age;
ObjectDataSource&&Gridview    
private int id;
ObjectDataSource&&Gridview    
private bool sex;
ObjectDataSource&&Gridview
ObjectDataSource&&Gridview    
private int newID
ObjectDataSource&&Gridview    
{
ObjectDataSource&&Gridview        
get
ObjectDataSource&&Gridview        
{
ObjectDataSource&&Gridview            
return IDseed++;
ObjectDataSource&&Gridview        }

ObjectDataSource&&Gridview    }

ObjectDataSource&&Gridview
ObjectDataSource&&Gridview    
public StudentData()
ObjectDataSource&&Gridview    
{ }
ObjectDataSource&&Gridview
ObjectDataSource&&Gridview    
public StudentData(string name, int age, bool sex)
ObjectDataSource&&Gridview    
{
ObjectDataSource&&Gridview        id 
= newID;
ObjectDataSource&&Gridview        
this.name = name;
ObjectDataSource&&Gridview        
this.age = age;
ObjectDataSource&&Gridview        
this.sex = sex;
ObjectDataSource&&Gridview    }

ObjectDataSource&&Gridview
ObjectDataSource&&Gridview    
public string Name
ObjectDataSource&&Gridview    
{
ObjectDataSource&&Gridview        
get return name; }
ObjectDataSource&&Gridview        
set { name = value; }
ObjectDataSource&&Gridview    }

ObjectDataSource&&Gridview
ObjectDataSource&&Gridview    
public int Age
ObjectDataSource&&Gridview    
{
ObjectDataSource&&Gridview        
get return age; }
ObjectDataSource&&Gridview        
set { age = value; }
ObjectDataSource&&Gridview    }

ObjectDataSource&&Gridview
ObjectDataSource&&Gridview    
public int ID
ObjectDataSource&&Gridview    
{
ObjectDataSource&&Gridview        
get return id; }
ObjectDataSource&&Gridview        
set { id = value; }
ObjectDataSource&&Gridview    }

ObjectDataSource&&Gridview
ObjectDataSource&&Gridview    
public bool Sex
ObjectDataSource&&Gridview    
{
ObjectDataSource&&Gridview        
get return sex; }
ObjectDataSource&&Gridview        
set { sex = value; }
ObjectDataSource&&Gridview    }

ObjectDataSource&&Gridview}

ObjectDataSource&&Gridview
 
注意:Students.cs必须放在App_Code目录里,或者编译后放在bin目录里,否则前面选择Business Object时找不到这个类。
 
 
今天只讨论了ASP.NET 2.0中GridView与DetailsView的联合使用的问题,GridView和DetailsView的用法的其它方面将会在后续的文章中陆续介绍。

你可能感兴趣的:(dataSource)