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接口即可)。
a.jpg
在GridView的Smart Tag中有Choose Data Source的选项,可以选取页面中已存在的DataSource。选定DataSource后可以点击Configure Data Source,会出现下面的界面
b.jpg在其中可以选择一个类,这个类的类名将会作为ObjectDataSource的TypeName属性。然后Next下去…
c.jpg在这可以选择select、update、insert和delete分别对应的方法。但可以不选。一个ObjectDataSource的select方法是必须要有的,如果没有在这个界面中选择的话,可以在Page_Load方法中根据需要指定,例如(这个小示例与下面的例子无关):
 
 1 None.gif     void  Page_Load( object  sender, EventArgs e)
 2 ExpandedBlockStart.gifContractedBlock.gif     dot.gif {
 3InBlock.gif        if (!Page.IsPostBack)
 4ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 5InBlock.gif            if (Page.User.IsInRole("Administrator"))
 6ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 7InBlock.gif                ObjectDataSource1.SortParameterName = "sortParameter";
 8InBlock.gif                ObjectDataSource1.SelectMethod = "GetStudents";
 9ExpandedSubBlockEnd.gif            }

10InBlock.gif            else
11ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
12InBlock.gif                ObjectDataSource1.SelectParameters.Add(new Parameter("Name", TypeCode.Int32, Page.User.Identity.Name));
13InBlock.gif                ObjectDataSource1.SortParameterName = "sortParameter";
14InBlock.gif                ObjectDataSource1.SelectMethod = "SelectStudent";
15ExpandedSubBlockEnd.gif            }

16ExpandedSubBlockEnd.gif        }

17ExpandedBlockEnd.gif}
 
对于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方法应该接收一个参数(一般应该是返回类型的主键),用以确定显示哪个实例的具体信息。
d.jpg
在接下来的Wizard中
e.jpg要选取这个参数的数据源。注意右边的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就可以配合使用了。下面是一个例子:
页面文件:
ExpandedBlockStart.gif ContractedBlock.gif <% dot.gif @ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"  %>
None.gif
None.gif
<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd" >
None.gif
< html  xmlns ="http://www.w3.org/1999/xhtml" >
None.gif
< head  runat ="server" >
None.gif    
< title > Untitled Page </ title >
None.gif
</ head >
None.gif
< body >
None.gif    
< form  id ="form1"  runat ="server" >
None.gif        
< asp:ObjectDataSource  ID ="ObjectDataSource1"  runat ="server"  InsertMethod ="InsertStudent"  SelectMethod ="GetStudents"  TypeName ="Student"  UpdateMethod ="UpdateStudent"  OldValuesParameterFormatString ="Original_{0}"  DataObjectTypeName ="StudentData"  DeleteMethod ="DeleteStudent" >
None.gif        
</ asp:ObjectDataSource >
None.gif        
< div >
None.gif            
< asp:GridView  ID ="GridView1"  runat ="server"  AllowSorting ="True"  CellPadding ="4"  DataSourceID ="ObjectDataSource1"  ForeColor ="#333333"  GridLines ="None"  DataKeyNames ="ID"  AutoGenerateColumns ="False" >
None.gif                
< FooterStyle  BackColor ="#507CD1"  Font-Bold ="True"  ForeColor ="White"   />
None.gif                
< RowStyle  BackColor ="#EFF3FB"   />
None.gif                
< Columns >
None.gif                    
< asp:CommandField  ShowSelectButton ="True"   />
None.gif                    
< asp:BoundField  DataField ="Name"  HeaderText ="Name"  SortExpression ="Name"   />
None.gif                
</ Columns >
None.gif                
< PagerStyle  BackColor ="#2461BF"  ForeColor ="White"  HorizontalAlign ="Center"   />
None.gif                
< SelectedRowStyle  BackColor ="#D1DDF1"  Font-Bold ="True"  ForeColor ="#333333"   />
None.gif                
< HeaderStyle  BackColor ="#507CD1"  Font-Bold ="True"  ForeColor ="White"   />
None.gif                
< EditRowStyle  BackColor ="#2461BF"   />
None.gif                
< AlternatingRowStyle  BackColor ="White"   />
None.gif            
</ asp:GridView >
None.gif            
&nbsp;   &nbsp;
None.gif            
< asp:ObjectDataSource  ID ="ObjectDataSource2"  runat ="server"  DataObjectTypeName ="StudentData"
None.gif                DeleteMethod
="DeleteStudent"  InsertMethod ="InsertStudent"  SelectMethod ="SelectStudent"
None.gif                TypeName
="Student"  UpdateMethod ="UpdateStudent" >
None.gif                
< SelectParameters >
None.gif                    
< asp:ControlParameter  ControlID ="GridView1"  Name ="i"  PropertyName ="SelectedValue"
None.gif                        Type
="Int32"   />
None.gif                
</ SelectParameters >
None.gif            
</ asp:ObjectDataSource >
None.gif            
&nbsp;&nbsp;
None.gif        
</ div >
None.gif        
< 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" >
None.gif            
< FooterStyle  BackColor ="#507CD1"  Font-Bold ="True"  ForeColor ="White"   />
None.gif            
< CommandRowStyle  BackColor ="#D1DDF1"  Font-Bold ="True"   />
None.gif            
< RowStyle  BackColor ="#EFF3FB"   />
None.gif            
< FieldHeaderStyle  BackColor ="#DEE8F5"  Font-Bold ="True"   />
None.gif            
< PagerStyle  BackColor ="#2461BF"  ForeColor ="White"  HorizontalAlign ="Left"   />
None.gif            
< Fields >
None.gif                
< asp:BoundField  DataField ="Age"  HeaderText ="Age"  SortExpression ="Age"   />
None.gif                
< asp:BoundField  DataField ="Name"  HeaderText ="Name"  SortExpression ="Name"   />
None.gif                
< asp:CheckBoxField  DataField ="Sex"  HeaderText ="Sex"  SortExpression ="Sex"   />
None.gif                
< asp:CommandField  ShowDeleteButton ="True"  ShowEditButton ="True"  ShowInsertButton ="True"   />
None.gif            
</ Fields >
None.gif            
< HeaderStyle  BackColor ="#507CD1"  Font-Bold ="True"  ForeColor ="White"   />
None.gif            
< EditRowStyle  BackColor ="#2461BF"   />
None.gif            
< AlternatingRowStyle  BackColor ="White"   />
None.gif        
</ asp:DetailsView >
None.gif    
</ form >
None.gif
</ body >
None.gif
</ html >
None.gif
后台代码:
Default.aspx.cs
None.gif using  System;
None.gif
using  System.Data;
None.gif
using  System.Configuration;
None.gif
using  System.Web;
None.gif
using  System.Web.Security;
None.gif
using  System.Web.UI;
None.gif
using  System.Web.UI.WebControls;
None.gif
using  System.Web.UI.WebControls.WebParts;
None.gif
using  System.Web.UI.HtmlControls;
None.gif
None.gif
public  partial  class  _Default : System.Web.UI.Page 
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
protected void Page_Load(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        DetailsView1.ItemCreated 
+= delegate(object s, EventArgs ee)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            GridView1.DataBind();
ExpandedSubBlockEnd.gif        }
;
InBlock.gif
InBlock.gif        DetailsView1.ItemDeleted 
+= delegate(object s, DetailsViewDeletedEventArgs ee)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            GridView1.DataBind();
ExpandedSubBlockEnd.gif        }
;
InBlock.gif
InBlock.gif        DetailsView1.ItemUpdated 
+= delegate(object s, DetailsViewUpdatedEventArgs ee)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            GridView1.DataBind();
ExpandedSubBlockEnd.gif        }
;
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedBlockEnd.gif}

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

ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public List<StudentData> GetStudents()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
return students;
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public StudentData SelectStudent(int i)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
foreach (StudentData student in students)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (student.ID == i)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return student;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif        
//如果返回一个null,则所绑定的控件将不会显示
InBlock.gif
        return null;
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public void InsertStudent(StudentData stuData)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        students.Add(stuData);
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public void UpdateStudent(StudentData stuData)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
foreach (StudentData student in students)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (student.ID == stuData.ID)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                student.Name 
= stuData.Name;
InBlock.gif                student.Age 
= stuData.Age;
InBlock.gif                student.Sex 
= stuData.Sex;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public void DeleteStudent(StudentData stuData)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        StudentData theStudent 
= new StudentData();
InBlock.gif        
foreach (StudentData student in students)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (student.ID == stuData.ID)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                theStudent 
= student;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif        students.Remove(theStudent);
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
None.gif
public   class  StudentData
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
static private int IDseed = 1;
InBlock.gif    
private string name;
InBlock.gif    
private int age;
InBlock.gif    
private int id;
InBlock.gif    
private bool sex;
InBlock.gif
InBlock.gif    
private int newID
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
get
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return IDseed++;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public StudentData()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{ }
InBlock.gif
InBlock.gif    
public StudentData(string name, int age, bool sex)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        id 
= newID;
InBlock.gif        
this.name = name;
InBlock.gif        
this.age = age;
InBlock.gif        
this.sex = sex;
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public string Name
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
get dot.gifreturn name; }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
set dot.gif{ name = value; }
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public int Age
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
get dot.gifreturn age; }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
set dot.gif{ age = value; }
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public int ID
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
get dot.gifreturn id; }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
set dot.gif{ id = value; }
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public bool Sex
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
get dot.gifreturn sex; }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
set dot.gif{ sex = value; }
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

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

转载于:https://www.cnblogs.com/raymond19840709/archive/2006/09/28/517504.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值