您的位置:首页 > 编程语言 > ASP

ASP.NET 2.0中GridView与DetailsView的联合使用

2008-01-08 16:15 483 查看
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接口即可)。



在GridView的Smart Tag中有Choose Data Source的选项,可以选取页面中已存在的DataSource。选定DataSource后可以点击Configure Data Source,会出现下面的界面


在其中可以选择一个类,这个类的类名将会作为ObjectDataSource的TypeName属性。然后Next下去…


在这可以选择select、update、insert和delete分别对应的方法。但可以不选。一个ObjectDataSource的select方法是必须要有的,如果没有在这个界面中选择的话,可以在Page_Load方法中根据需要指定,例如(这个小示例与下面的例子无关):

1

void Page_Load(object sender, EventArgs e)
2





{
3

if (!Page.IsPostBack)
4





{
5

if (Page.User.IsInRole("Administrator"))
6





{
7

ObjectDataSource1.SortParameterName = "sortParameter";
8

ObjectDataSource1.SelectMethod = "GetStudents";
9

}
10

else
11





{
12

ObjectDataSource1.SelectParameters.Add(new Parameter("Name", TypeCode.Int32, Page.User.Identity.Name));
13

ObjectDataSource1.SortParameterName = "sortParameter";
14

ObjectDataSource1.SelectMethod = "SelectStudent";
15

}
16

}
17

}

[align=left] [/align]
[align=left]对于GridView的数据显示,一个常见的问题是:它根据什么生成行,又根据什么生成列呢?GridView需要的数据源只需实现IEnumerable 或 ItypedList接口。所以ObjectDataSource的select方法的返回值也必然要遵守几个条件:实现IEnumerable 或 ItypedList接口或直接是DataSet。如果返回值是DataSet,GridView会根据DataSet中的第一个Table生成行和列。否则,将枚举每一个返回值作为一行,并根据返回值的类型应用反射技术找出它的public属性作为列(前提是AltoGenerateColumn属性设为true)。例如:select方法返回类型是List<StrudentData>[/align]
[align=left]StudentData类型有Name, Age, ID, Sex等属性,那么GridView就会将返回的每一个StudentData作为一行,并生成相应的Name, Age, ID, Sex列。[/align]
[align=left] [/align]
[align=left]DetailsView如果想要显示GridView当中选定行的详细信息,则需要新建一个ObjectDataSource,这个ObjectDataSource的TypeName一般与第一个ObjectDataSource的TypeName相同,但是它的select方法应该与第一个ObjectDataSource的不同。不同之处在于这个select方法应该接收一个参数(一般应该是返回类型的主键),用以确定显示哪个实例的具体信息。
[/align]
[align=left][/align]



在接下来的Wizard中

[align=left][/align]


要选取这个参数的数据源。注意右边的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列的值。
[align=left] [/align]
[align=left]在DetailsView中如果主键列不显示,也必须把主键列的列名赋值给DataKeyName属性(多个主键可以用逗号分开)。因为ViewState中只存放所显示列的值和在DataKeyName中指定的列的值。如果不赋值给DataKeyName的话,在DetailsView中使用Update、Delete方法的时候,主键列从ViewState中读取不到值,将会用默认值代替,这样就得不到想要的结果。[/align]
[align=left] [/align]
最后,介绍一下ObjectDataSource的DataObjectTypeName属性。我们在Update和Insert的时候往往需要多个参数代表对象的不同属性。这种做法首先容易出错,其次也不利于数据的封装。于是ObjectDataSource添加了一个DataObjectTypeName属性,这个属性确定了一个类,这个类可以封装要被修改或插入的值的全部属性值。在确定了这个属性后,在Update和Insert的函数中就可以用DataObjectTypeName属性定义的那个类作为参数类型。DataObjectTypeName的这种用法在下面的例子中可以看到。在调用在Update和Insert的时候,ASP.NET会自动实例化一个DataObjectTypeName属性定义的类型,并给它赋值,然后传给调用的函数。

做为DataObjectTypeName属性的类主要有以下三点要求:
1. 这个类必须有一个缺省的构造函数(就是0参数的构造函数)
2. 这个类的公有属性名必须和GridView或DetailsView所绑定的类的公有属性名相同
3. 这些公有属性必须get和set两种方法都具备。
[align=left] [/align]
经过上面的配置,GridView和DetailsView就可以配合使用了。下面是一个例子:
页面文件:




<%

@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>




<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">


<head runat="server">


<title>Untitled Page</title>


</head>


<body>


<form id="form1" runat="server">


<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" InsertMethod="InsertStudent" SelectMethod="GetStudents" TypeName="Student" UpdateMethod="UpdateStudent" OldValuesParameterFormatString="Original_{0}" DataObjectTypeName="StudentData" DeleteMethod="DeleteStudent">


</asp:ObjectDataSource>


<div>


<asp:GridView ID="GridView1" runat="server" AllowSorting="True" CellPadding="4" DataSourceID="ObjectDataSource1" ForeColor="#333333" GridLines="None" DataKeyNames="ID" AutoGenerateColumns="False">


<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />


<RowStyle BackColor="#EFF3FB" />


<Columns>


<asp:CommandField ShowSelectButton="True" />


<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />


</Columns>


<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />


<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />


<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />


<EditRowStyle BackColor="#2461BF" />


<AlternatingRowStyle BackColor="White" />


</asp:GridView>


   


<asp:ObjectDataSource ID="ObjectDataSource2" runat="server" DataObjectTypeName="StudentData"


DeleteMethod="DeleteStudent" InsertMethod="InsertStudent" SelectMethod="SelectStudent"


TypeName="Student" UpdateMethod="UpdateStudent">


<SelectParameters>


<asp:ControlParameter ControlID="GridView1" Name="i" PropertyName="SelectedValue"


Type="Int32" />


</SelectParameters>


</asp:ObjectDataSource>


  


</div>


<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">


<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />


<CommandRowStyle BackColor="#D1DDF1" Font-Bold="True" />


<RowStyle BackColor="#EFF3FB" />


<FieldHeaderStyle BackColor="#DEE8F5" Font-Bold="True" />


<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Left" />


<Fields>


<asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />


<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />


<asp:CheckBoxField DataField="Sex" HeaderText="Sex" SortExpression="Sex" />


<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowInsertButton="True" />


</Fields>


<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />


<EditRowStyle BackColor="#2461BF" />


<AlternatingRowStyle BackColor="White" />


</asp:DetailsView>


</form>


</body>


</html>



后台代码:
Default.aspx.cs


using System;


using System.Data;


using System.Configuration;


using System.Web;


using System.Web.Security;


using System.Web.UI;


using System.Web.UI.WebControls;


using System.Web.UI.WebControls.WebParts;


using System.Web.UI.HtmlControls;




public partial class _Default : System.Web.UI.Page






{


protected void Page_Load(object sender, EventArgs e)






{


DetailsView1.ItemCreated += delegate(object s, EventArgs ee)






{


GridView1.DataBind();


};




DetailsView1.ItemDeleted += delegate(object s, DetailsViewDeletedEventArgs ee)






{


GridView1.DataBind();


};




DetailsView1.ItemUpdated += delegate(object s, DetailsViewUpdatedEventArgs ee)






{


GridView1.DataBind();


};


}




}



App_Code/Students.cs


using System;


using System.Data;


using System.Configuration;


using System.Web;


using System.Collections.Generic;


using System.Web.Security;


using System.Web.UI;


using System.Web.UI.WebControls;


using System.Web.UI.WebControls.WebParts;


using System.Web.UI.HtmlControls;




public class Student






{


static private List<StudentData> students;




public Student()






{


if (students == null)






{


students = new List<StudentData>();


StudentData data = new StudentData("Chiewen Ly", 23, true);


students.Add(data);




data = new StudentData("A~ Foo", 24, false);


students.Add(data);




data = new StudentData("lyg", 25, true);


students.Add(data);




}


}




public List<StudentData> GetStudents()






{


return students;


}




public StudentData SelectStudent(int i)






{


foreach (StudentData student in students)






{


if (student.ID == i)






{


return student;


}


}


//如果返回一个null,则所绑定的控件将不会显示


return null;


}




public void InsertStudent(StudentData stuData)






{


students.Add(stuData);


}




public void UpdateStudent(StudentData stuData)






{


foreach (StudentData student in students)






{


if (student.ID == stuData.ID)






{


student.Name = stuData.Name;


student.Age = stuData.Age;


student.Sex = stuData.Sex;


}


}


}




public void DeleteStudent(StudentData stuData)






{


StudentData theStudent = new StudentData();


foreach (StudentData student in students)






{


if (student.ID == stuData.ID)






{


theStudent = student;


}


}


students.Remove(theStudent);


}


}




public class StudentData






{


static private int IDseed = 1;


private string name;


private int age;


private int id;


private bool sex;




private int newID






{


get






{


return IDseed++;


}


}




public StudentData()






{ }




public StudentData(string name, int age, bool sex)






{


id = newID;


this.name = name;


this.age = age;


this.sex = sex;


}




public string Name






{




get

{ return name; }




set

{ name = value; }


}




public int Age






{




get

{ return age; }




set

{ age = value; }


}




public int ID






{




get

{ return id; }




set

{ id = value; }


}




public bool Sex






{




get

{ return sex; }




set

{ sex = value; }


}


}



注意:Students.cs必须放在App_Code目录里,或者编译后放在bin目录里,否则前面选择Business Object时找不到这个类。

今天只讨论了ASP.NET 2.0中GridView与DetailsView的联合使用的问题,GridView和DetailsView的用法的其它方面将会在后续的文章中陆续介绍。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐