GridView,DataList,DetailsView,FormView,ListView,Repeater,DataPager

本文深入探讨了ASP.NET中的多种数据控件,包括GridView、DetailsView、FormView、Repeater和DataList的特点及应用场景。重点讲解了这些控件如何绑定数据源、支持自定义布局及实现数据操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Net 2.0中5个数据源控件,GridView,DataList,Repeater ,DetailsView,FormView
(1)其中前3个用于呈现多列数据,后面2个用于呈现单列数据,即常用的数据明细.
(2)GridView和DetailsView控件的布局固定,自定义数据显示的布局功能有限,一般适合布局简单的数据呈现.
(3)DataList,Repeater和FormView数据控件都有很强的自定义布局能力,如果数据呈现需要较为复杂的布局方案,这3个控件是首选
.

(4)GridView ,DetailsView和FormView都是2.0版本新增控件,内置了分页,排序等等功能,其改进程度是1.1所提供控件无法比的.
(5)DataList和Repeater是1.1版就提供的控件,内置功能较弱,需要自己实现分页,排序,数据事件等功能.

     有趣的是,在现在的Aspnet平台上,如果从功能上来说呈现单列数据时DetailsView和FormView相对应,DetailsView布局固定FormView自定义布局,呈现多列数据时只有GridView来负责布局固定的数据,从功能上来说,没有对应的控件与GridView相配.
DataList提供的数据功能与GridView相比,实在是太弱了.与GridView几乎不需要编程就能担负数据呈现的重任相比,DataList要求程序员必须自己写代码来实现想要的功能.推测是为了与1.1兼容,所以没有升级DataList.为了赶进度,所以没有像升级DataGrid为GridView一样升级DataList为ListView....

 

GridView 控件
http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.gridview.aspx

GridView 控件以表的形式显示数据,并提供对列进行排序、分页、翻阅数据以及编辑或删除单个记录的功能。在表中显示数据源的值,其中每列表示一个字段,每行表示一条记录。

GridView 控件支持下面的功能:

  • 绑定至数据源控件,如 SqlDataSource

  • 内置排序功能。

  • 内置更新和删除功能。

  • 内置分页功能。

  • 内置行选择功能。

  • 以编程方式访问 GridView 对象模型以动态设置属性、处理事件等。

  • 多个键字段。

  • 用于超链接列的多个数据字段。

  • 可通过主题和样式进行自定义的外观.

绑定到数据

GridView 控件可绑定到数据源控件(如 SqlDataSourceObjectDataSource 等等),以及实现 System.Collections..::.IEnumerable 接口的任何数据源(如 System.Data..::.DataViewSystem.Collections..::.ArrayListSystem.Collections..::.Hashtable)。使用以下方法之一将 GridView 控件绑定到适当的数据源类型:

  • 若要绑定到某个数据源控件,请将 GridView 控件的 DataSourceID 属性设置为该数据源控件的 ID 值。GridView 控件自动绑定到指定的数据源控件,并且可利用该数据源控件的功能来执行排序、更新、删除和分页。这是绑定到数据的首选方法。

  • 若要绑定到某个实现 System.Collections..::.IEnumerable 接口的数据源,请以编程方式将 GridView 控件的 DataSource 属性设置为该数据源,然后调用 DataBind 方法. 当使用此方法时,GridView 控件不提供内置的排序、更新、删除和分页功能。需要使用适当的事件提供此功能。

GridView 控件不直接支持将记录插入数据源。但是,通过将 GridView 控件与 DetailsViewFormView 控件结合使用则可以插入记录。

注意:GridView 控件是 ASP.NET 的早期版本中提供的 DataGrid 控件的后继控件。除了添加利用数据源控件功能的新功能,GridView 控件还实现了某些改进,例如,定义多个主键字段的功能、使用绑定字段和模板的改进用户界面自定义以及用于处理或取消事件的新模型。          有关更多信息,请参见 GridView Web 服务器控件和比较 GridView 和 DataGrid Web 服务器控件。

 

DetailsView 控件
http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.detailsview.aspx

DetailsView 控件一次呈现一条表格形式的记录,并提供翻阅多条记录以及插入、更新和删除记录的功能。DetailsView 控件通常用在主/详细信息方案中,在这种方案中,主控件(如 GridView 控件)中的所选记录决定了 DetailsView 控件显示的记录。

DetailsView 控件支持下面的功能:

  • 绑定至数据源控件,如 SqlDataSource

  • 内置插入功能。

  • 内置更新和删除功能。

  • 内置分页功能。

  • 以编程方式访问 DetailsView 对象模型以动态设置属性、处理事件等。

  • 可通过主题和样式进行自定义的外观。

ContractedBlock.gif ExpandedBlockStart.gif Code
<%@ Page Language="C#" %>
<html>
<head id="Head1" runat="server">
  
<title>GridView DetailsView Master-Details (1 Page)</title>
</head>
<body>
  
<form id="form1" runat="server">
    
<b>Choose a category:</b>
    
    
<asp:DropDownList ID="DropDownList1" DataSourceID="SqlDataSource2" AutoPostBack="True"
      DataTextField
="CategoryName" runat="server" DataValueField="CategoryID" />
      
    
<asp:SqlDataSource ID="SqlDataSource2" runat="server" SelectCommand="SELECT * FROM [Categories]" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
       
/>
    
<br />
    
<br />
    
<table>
      
<tr>
        
<td valign="top" style="width: 288px">
        
          
<asp:GridView ID="GridView1" AllowSorting="True" AllowPaging="True" runat="server"
            DataSourceID
="SqlDataSource1" DataKeyNames="productid"
            AutoGenerateColumns
="true" Width="427px" CellPadding="4" ForeColor="#333333" GridLines="None" Font-Names="Verdana" Font-Size="XX-Small">
              
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
              
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
              
<EditRowStyle BackColor="#999999" />
              
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
              
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
              
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
              
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                
<Columns>
                     
<asp:CommandField ShowSelectButton="True" />
                
</Columns>
          
</asp:GridView>
          
          
<asp:SqlDataSource ID="SqlDataSource1" runat="server" SelectCommand="SELECT productid,[ProductName], [CategoryID], [InStore], [Description] FROM [Products] where Categoryid=@CategoryID"
            ConnectionString
="<%$ ConnectionStrings:ConnectionString %>">
             
<SelectParameters>
              
<asp:ControlParameter ControlID="DropDownList1" Name="categoryid" PropertyName="SelectedValue"
                Type
="String" />
            
</SelectParameters>
          
</asp:SqlDataSource>
          
        
</td>
        
<td valign="top">
        
          
<asp:DetailsView AutoGenerateRows="true" DataSourceID="SqlDataSource3"
            HeaderText
="Author Details" ID="DetailsView1" runat="server" Width="275px" CellPadding="4" Font-Names="Verdana" Font-Size="XX-Small" ForeColor="#333333" GridLines="None">
              
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
              
<CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
              
<EditRowStyle BackColor="#999999" />
              
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
              
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
              
<FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" />
              
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
              
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
          
</asp:DetailsView>
          
          
<asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ID="SqlDataSource3"
            runat
="server" SelectCommand="SELECT * FROM [Products] where productid=@productid">
              
<SelectParameters>
                 
<asp:ControlParameter ControlID="GridView1" Name="Productid" PropertyName="SelectedValue" Type="String" />
                 
<%--Name="productid" 为变量的名称,对应SelectCommand="SELECT * FROM [Products] where productid=@productid",不区分大小写!!!--%>
                 
<%--ControlParameter 类还提供两个属性:ControlID 和 PropertyName。ControlID 属性标识要绑定到哪一个 Control 实例;PropertyName 属性标识 ControlParameter 类从其中检索值的 Control 的公共属性--%>
              
</SelectParameters>
          
</asp:SqlDataSource>
          
        
</td>
      
</tr>
    
</table>
    
<br />
  
</form>
</body>
</html>

FormView 控件

http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.formview.aspx
FormView 控件与 DetailsView 控件类似,它一次呈现数据源中的一条记录,并提供翻阅多条记录以及插入、更新和删除记录的功能。不过,FormView 控件与 DetailsView 控件之间的差别在于:DetailsView 控件使用基于表格的布局,在这种布局中,数据记录的每个字段都显示为控件中的一行。而 FormView 控件则不指定用于显示记录的预定义布局。实际上,您将创建包含控件的模板,以显示记录中的各个字段。该模板包含用于设置窗体布局的格式、控件和绑定表达式。

FormView 控件支持以下功能:

  • 绑定到数据源控件,如 SqlDataSourceObjectDataSource

  • 内置插入功能。

  • 内置更新和删除功能。

  • 内置分页功能。

  • 以编程方式访问 FormView 对象模型以动态设置属性、处理事件等。

  • 可通过用户定义的模板、主题和样式自定义外观。

ContractedBlock.gif ExpandedBlockStart.gif Code
<%@ Page language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
  
<head runat="server">
    
<title>FormView Example</title>
</head>
<body>
    
<form id="form1" runat="server">

      
<h3>FormView Example</h3>

      
<asp:formview id="EmployeeFormView"
        datasourceid
="EmployeeSource"
        allowpaging
="true"
        datakeynames
="EmployeeID" 
        runat
="server">

        
<itemtemplate>

          
<table>
            
<tr>
              
<td>
                
<asp:image id="EmployeeImage"
                  imageurl
='<%# Eval("PhotoPath") %>'
                  alternatetext
='<%# Eval("LastName") %>' 
                  runat
="server"/>
              
</td>
              
<td>
                
<h3><%# Eval("FirstName"%>&nbsp;<%# Eval("LastName"%></h3>      
                
<%# Eval("Title"%>        
              
</td>
            
</tr>
          
</table>

        
</itemtemplate>

        
<pagersettings position="Bottom"
          mode
="NextPrevious"/> 

      
</asp:formview>

      
<!-- This example uses Microsoft SQL Server and connects  -->
      
<!-- to the Northwind sample database. Use an ASP.NET     -->
      
<!-- expression to retrieve the connection string value   -->
      
<!-- from the Web.config file.                            -->
      
<asp:sqldatasource id="EmployeeSource"
        selectcommand
="Select [EmployeeID], [LastName], [FirstName], [Title], [PhotoPath] From [Employees]"
        connectionstring
="<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat
="server"/>

    
</form>
  
</body>
</html>

 

ContractedBlock.gif ExpandedBlockStart.gif Code
<%@ Page language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  
void EmployeeFormView_ItemUpdating(Object sender, FormViewUpdateEventArgs e)
ExpandedBlockStart.gifContractedBlock.gif  
{

    
// Validate the field values entered by the user. This
    
// example determines whether the user left any fields
    
// empty. Use the NewValues property to access the new 
    
// values entered by the user.
    ArrayList emptyFieldList = ValidateFields(e.NewValues);

    
if (emptyFieldList.Count > 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{

      
// The user left some fields empty. Display an error message.

      
// Use the Keys property to retrieve the key field value.
      String keyValue = e.Keys["EmployeeID"].ToString();

      MessageLabel.Text 
= "You must enter a value for each field of record " +
        keyValue 
+ ".<br/>The following fields are missing:<br/><br/>";

      
// Display the missing fields.
      foreach (String value in emptyFieldList)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
{
        
// Use the OldValues property to access the original value
        
// of a field.
        MessageLabel.Text += value + " - Original Value = " + 
          e.OldValues[value].ToString() 
+ "<br />";
      }


      
// Cancel the update operation.
      e.Cancel = true;

    }

    
else
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
      
// The field values passed validation. Clear the
      
// error message label.
      MessageLabel.Text = "";
    }


  }


  ArrayList ValidateFields(IOrderedDictionary list)
ExpandedBlockStart.gifContractedBlock.gif  
{

    
// Create an ArrayList object to store the
    
// names of any empty fields.
    ArrayList emptyFieldList = new ArrayList();

    
// Iterate though the field values entered by
    
// the user and check for an empty field. Empty
    
// fields contain a null value.
    foreach (DictionaryEntry entry in list)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
      
if (entry.Value == String.Empty)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
{
        
// Add the field name to the ArrayList object.
        emptyFieldList.Add(entry.Key.ToString());
      }

    }


    
return emptyFieldList;
  }


  
void EmployeeFormView_ModeChanging(Object sender, FormViewModeEventArgs e)
ExpandedBlockStart.gifContractedBlock.gif  
{
    
if (e.CancelingEdit)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
      
// The user canceled the update operation.
      
// Clear the error message label.
      MessageLabel.Text = "";
    }

  }


</script>

<html  >
  
<head runat="server">
    
<title>FormView Example</title>
</head>
<body>
    
<form id="form1" runat="server">

      
<h3>FormView Example</h3>

      
<asp:formview id="EmployeeFormView"
        datasourceid
="EmployeeSource"
        allowpaging
="true"
        datakeynames
="EmployeeID"
        headertext
="Employee Record"
        emptydatatext
="No employees found."
        onitemupdating
="EmployeeFormView_ItemUpdating"
        onmodechanging
="EmployeeFormView_ModeChanging"  
        runat
="server">

        
<headerstyle backcolor="CornFlowerBlue"
          forecolor
="White"
          font
-size="14"
          horizontalalign
="Center"  
          wrap
="false"/>
        
<rowstyle backcolor="LightBlue"
          wrap
="false"/>
        
<pagerstyle backcolor="CornFlowerBlue"/>

        
<itemtemplate>
          
<table>
            
<tr>
              
<td rowspan="6">
                
<asp:image id="EmployeeImage"
                  imageurl
='<%# Eval("PhotoPath") %>'
                  alternatetext
='<%# Eval("LastName") %>' 
                  runat
="server"/>
              
</td>
              
<td colspan="2">
                  
&nbsp; 
              
</td>
            
</tr>
            
<tr>
              
<td>
                
<b>Name:</b>
              
</td>
              
<td>
                
<%# Eval("FirstName"%> <%# Eval("LastName"%>
              
</td>
            
</tr>
            
<tr>
              
<td>
                
<b>Title:</b>
              
</td>
              
<td>
                
<%# Eval("Title"%>
              
</td>
            
</tr>
            
<tr>
              
<td>
                
<b>Hire Date:</b>                 
              
</td>
              
<td>
                
<%# Eval("HireDate","{0:d}"%>
              
</td>
            
</tr>
            
<tr style="height:150; vertical-align:top">
              
<td>
                
<b>Address:</b>
              
</td>
              
<td>
                
<%# Eval("Address"%><br/>
                
<%# Eval("City"%> <%# Eval("Region"%>
                
<%# Eval("PostalCode"%><br/>
                
<%# Eval("Country"%>   
              
</td>
            
</tr>
            
<tr>
              
<td colspan="2">
                
<asp:linkbutton id="Edit"
                  text
="Edit"
                  commandname
="Edit"
                  runat
="server"/> 
              
</td>
            
</tr>
          
</table>       
        
</itemtemplate>
        
<edititemtemplate>
          
<table>
            
<tr>
              
<td rowspan="6">
                
<asp:image id="EmployeeEditImage"
                  imageurl
='<%# Eval("PhotoPath") %>'
                  alternatetext
='<%# Eval("LastName") %>' 
                  runat
="server"/>
              
</td>
              
<td colspan="2">
                  
&nbsp; 
              
</td>
            
</tr>
            
<tr>
              
<td>
                
<b>Name:</b>
              
</td>
              
<td>
                
<asp:textbox id="FirstNameUpdateTextBox"
                  text
='<%# Bind("FirstName") %>'
                  runat
="server"/>
                
<asp:textbox id="LastNameUpdateTextBox"
                  text
='<%# Bind("LastName") %>'
                  runat
="server"/>
              
</td>
            
</tr>
            
<tr>
              
<td>
                
<b>Title:</b>
              
</td>
              
<td>
                
<asp:textbox id="TitleUpdateTextBox"
                  text
='<%# Bind("Title") %>'
                  runat
="server"/> 
              
</td>
            
</tr>
            
<tr>
              
<td>
                
<b>Hire Date:</b>                 
              
</td>
              
<td>
                
<asp:textbox id="HireDateUpdateTextBox"
                  text
='<%# Bind("HireDate", "{0:d}") %>'
                  runat
="server"/>
              
</td>
            
</tr>
            
<tr style="height:150; vertical-align:top">
              
<td>
                
<b>Address:</b>
              
</td>
              
<td>
                
<asp:textbox id="AddressUpdateTextBox"
                  text
='<%# Bind("Address") %>'
                  runat
="server"/>
                
<br/>
                
<asp:textbox id="CityUpdateTextBox"
                  text
='<%# Bind("City") %>'
                  runat
="server"/> 
                
<asp:textbox id="RegionUpdateTextBox"
                  text
='<%# Bind("Region") %>'
                  width
="40"
                  runat
="server"/>
                
<asp:textbox id="PostalCodeUpdateTextBox"
                  text
='<%# Bind("PostalCode") %>'
                  width
="60"
                  runat
="server"/>
                
<br/>
                
<asp:textbox id="CountryUpdateTextBox"
                  text
='<%# Bind("Country") %>'
                  runat
="server"/> 
              
</td>
            
</tr>
            
<tr>
              
<td colspan="2">
                
<asp:linkbutton id="UpdateButton"
                  text
="Update"
                  commandname
="Update"
                  runat
="server"/>
                
<asp:linkbutton id="CancelButton"
                  text
="Cancel"
                  commandname
="Cancel"
                  runat
="server"/> 
              
</td>
            
</tr>
          
</table>       
        
</edititemtemplate>

        
<pagersettings position="Bottom"
          mode
="Numeric"/> 

      
</asp:formview>

      
<br/><br/>

      
<asp:label id="MessageLabel"
          forecolor
="Red"
          runat
="server"/>

      
<!-- This example uses Microsoft SQL Server and connects  -->
      
<!-- to the Northwind sample database. Use an ASP.NET     -->
      
<!-- expression to retrieve the connection string value   -->
      
<!-- from the Web.config file.                            -->
      
<asp:sqldatasource id="EmployeeSource"
        selectcommand
="Select [EmployeeID], [LastName], [FirstName], [Title], [Address], [City], [Region], [PostalCode], [Country], [HireDate], [PhotoPath] From [Employees]"
        updatecommand
="Update [Employees] Set [LastName]=@LastName, [FirstName]=@FirstName, [Title]=@Title, [Address]=@Address, [City]=@City, [Region]=@Region, [PostalCode]=@PostalCode, [Country]=@Country Where [EmployeeID]=@EmployeeID"
        connectionstring
="<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat
="server"/>

    
</form>
  
</body>
</html>

 

Repeater 控件
http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.repeater.aspx

     Repeater 控件使用数据源返回的一组记录呈现只读列表。与 FormView 控件类似,Repeater 控件不指定内置布局。您可以使用模板创建 Repeater 控件的布局。

     Repeater 控件是一个基本模板数据绑定列表。它没有内置的布局或样式,因此必须在该控件的模板内显式声明所有的布局、格式设置和样式标记。

     Repeater 控件是唯一允许在模板间拆分标记的 Web 控件。若要利用模板创建表,请在 HeaderTemplate 中包含表开始标记 (<table>),在 ItemTemplate 中包含单个表行标记 (<tr>),并在 FooterTemplate 中包含表结束标记 (</table>)。

ContractedBlock.gif ExpandedBlockStart.gif Code
下面的代码示例演示如何使用 DataSourceID 属性指定 Repeater 控件的数据源。DataSourceID 属性设置为 SqlDataSource 控件的 ID 属性,该控件用于检索数据。加载页面时,Repeater 控件自动绑定到 SqlDataSource 控件指定的数据源,并向用户显示该数据。

<%@ page language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
  
<head>
    
<title>Repeater.DataSourceID Property Example</title>
</head>

  
<body>
    
<form id="Form1" runat="server">

      
<h3>Repeater.DataSourceID Property Example</h3>

      
<asp:repeater id="Repeater1"       
        datasourceid
="SqlDataSource1"
        runat
="server">

        
<headertemplate>
          
<table border="1">
            
<tr>
              
<td><b>Product ID</b></td>
              
<td><b>Product Name</b></td>
            
</tr>
        
</headertemplate>

        
<itemtemplate>
          
<tr>
            
<td> <%# Eval("ProductID"%> </td>
            
<td> <%# Eval("ProductName"%> </td>
          
</tr>
        
</itemtemplate>

        
<footertemplate>
          
</table>
        
</footertemplate>
      
</asp:repeater>

            
<asp:sqldatasource id="SqlDataSource1"          
            connectionstring
="<%$ ConnectionStrings:NorthWindConnection%>" 
        selectcommand
="SELECT ProductID, ProductName FROM [Products] Where ProductID <= 10"
        runat
="server">
      
</asp:sqldatasource>

    
</form>      
  
</body>
</html>

 

DataList 控件

http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.datalist.aspx
DataList 控件以表的形式呈现数据,通过该控件,您可以使用不同的布局来显示数据记录,例如,将数据记录排成列或行的形式。您可以对 DataList 控件进行配置,使用户能够编辑或删除表中的记录。(DataList 控件不使用数据源控件的数据修改功能;您必须自己提供此代码。)DataList 控件与 Repeater 控件的不同之处在于:DataList 控件将项显式放在 HTML 表中,而 Repeater 控件则不然。

DataList 控件的显示方向可以是垂直或水平的。设置 RepeatDirection 属性以指定显示方向。

DataList 控件的布局由 RepeatLayout 属性控制。将此属性设置为 RepeatLayout.Table 将以表的形式显示 DataList;而设置为 RepeatLayout.Flow 将显示不具有表结构的 DataList。

ContractedBlock.gif ExpandedBlockStart.gif Code
<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
   
<script runat="server">

      ICollection CreateDataSource() 
      {

         
// Create sample data for the DataList control.
         DataTable dt = new DataTable();
         DataRow dr;

         
// Define the columns of the table.
         dt.Columns.Add(new DataColumn("IntegerValue"typeof(Int32)));
         dt.Columns.Add(
new DataColumn("StringValue"typeof(String)));
         dt.Columns.Add(
new DataColumn("CurrencyValue"typeof(double)));
         dt.Columns.Add(
new DataColumn("ImageValue"typeof(String)));

         
// Populate the table with sample values.
         for (int i = 0; i < 9; i++
         {
            dr 
= dt.NewRow();

            dr[
0= i;
            dr[
1= "Description for item " + i.ToString();
            dr[
2= 1.23 * (i + 1);
            dr[
3= "Image" + i.ToString() + ".jpg";

            dt.Rows.Add(dr);
         }

         DataView dv 
= new DataView(dt);
         
return dv;
      }


      
void Page_Load(Object sender, EventArgs e) 
      {

         
// Load sample data only once, when the page is first loaded.
         if (!IsPostBack) 
         {
            ItemsList.DataSource 
= CreateDataSource();
            ItemsList.DataBind();
         }

      }

   
</script>

<head runat="server">
    
<title>DataList Example</title>
</head>
<body>

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

      
<h3>DataList Example</h3>

      
<asp:DataList id="ItemsList"
           BorderColor
="black"
           CellPadding
="5"
           CellSpacing
="5"
           RepeatDirection
="Vertical"
           RepeatLayout
="Table"
           RepeatColumns
="3"
           runat
="server">

         
<HeaderStyle BackColor="#aaaadd">
         
</HeaderStyle>

         
<AlternatingItemStyle BackColor="Gainsboro">
         
</AlternatingItemStyle>

         
<HeaderTemplate>

            List of items

         
</HeaderTemplate>

         
<ItemTemplate>

            Description: 
<br />
            
<%# DataBinder.Eval(Container.DataItem, "StringValue"%>

            
<br />

            Price: 
<%# DataBinder.Eval(Container.DataItem, "CurrencyValue""{0:c}"%>

            
<br />

            
<asp:Image id="ProductImage" AlternateText="Product picture" 
                 ImageUrl
='<%# DataBinder.Eval(Container.DataItem, "ImageValue") %>'
                 runat
="server"/>

         
</ItemTemplate>

      
</asp:DataList>

   
</form>

</body>
</html>

 

引用 :

http://blog.youkuaiyun.com/skyaspnet/archive/2008/10/07/3029424.aspx

http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.listview.aspx

http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.datapager.aspx

原文地址:http://www.west-wind.com/WebLog/posts/127340.aspx
[译者改后源码下载]

原文发布日期:2007.08.02
作者:Rick Strahl
翻译:webabcd


介绍
今天,我花了几个小时的时间研究了一下ASP.NET 3.5中的ListView控件和DataPager控件。这两个控件是ASP.NET中新增的、非常受欢迎的控件。 ListView控件集成了DataGrid、DataList、Repeater和GridView控件的所有功能。它可以像Repeater控件那样,让我们在控件内写任何HTML代码。

可以说,ListView就是DataGrid和 Repeater的结合体,它既有Repeater控件的开放式模板,又具有DataGrid控件的编辑特性。这绝对是一个可以引起你兴趣的好东东,因为它给你提供了比DataGird丰富得多的布局手段,同时又具有DataGrid的所有特性。 ListView控件本身并不提供分页功能,但是我们可以通过另一个控件 – DataPager来实现分页的特性。把分页的特性单独放到另一个控件里,会给我们带来很多好处,比如说可以让别的控件使用它,又比如说我们可以把它放在页面的任何地方。实质上,DataPager就是一个扩展ListView分页功能的控件。


ListView控件
ListView是用来显示数据的,它的使用类似于Repeater控件。 ListView控件中有n多模板,出示如下:
    ·LayoutTemplate
    ·ItemTemplate
    ·AlternatingItemTemplate
    ·SelectedItemTemplate
    ·EmptyItemTemplate
    ·EmptyDataTemplate
    ·ItemSeparatorTemplate
    ·GroupTemplate
    ·GroupSeparatorTemplate
    ·EditItemTemplate
    ·InsertItemTemplate

它有很多的模板。 其中有许多新增的模板,如GroupTemplate和InsertItemTemplate。现在我们可能还无法了解GroupTemplate是如何工作的(后面会有介绍),但是对于InsertItemTemplate来说,一看就知道它是用于添加记录的(在之前的DataGird中是没有这个模板的)。

继续摸索这个控件后,我发现它可以让你在它的模板内写任何HTML标记或控件,这将给我们带来很大的自由度。


用ListView显示数据
开始,你可以把ListView当作是Repeater来使用,也就是说它是模板驱动型的控件,其中的LayoutTemplate是ListView的一个布局模板。 参考如下示例:

<asp:ListView ID="lvItems" runat="server"
              DataSourceID="Data"
              ItemContainerID="layoutTemplate"
              DataKeyNames="Pk"
>
    <Layouttemplate>               
        <div id="layoutTemplate" runat="server" />                       
    </Layouttemplate>       
       
    <ItemTemplate>
        <div class="itemdisplay">
        <b><%# Eval("Sku") %></b><br />
        <%# Eval("Abstract") %></div>
    </ItemTemplate>
</asp:ListView>



LayoutTemplate 用来决定包裹着详细内容的容器的标记。 你可以在布局模板内放置任何控件,不过它必须要是服务端控件(runat=”server”)。另外,你还需要指定ListView控件的ItemContainerID属性,它用来告知ListView在哪个容器下显示详细内容。在上面的例子中,LayoutTemplate其实并没有起到什么作用,因为它只是将ListView显示的详细内容放到了一个<div />标记下而已。 但是,我们也可以用它来显示复杂的布局,如<table />。 请看下面的例子,它就是用<table />来做ListView显示的详细内容的容器的,并且它还有一个固定表头的功能。

<asp:ListView ID="lvItemsTable" runat="server"
              DataSourceID="Data"
              ItemContainerID="layoutTableTemplate"
              DataKeyNames="Pk"             
>
    <LayoutTemplate>
        <div class="blackborder"  style="overflow-y:auto;height:500px;width:800px;">
        <table cellpadding="5" >
        <thead style="position:relative;">
        <tr class="gridheader" style="height:30px;">
            <th style="position:relative">Sku</th><th style="position:relative">Abstract</th>
        </tr>
        </thead>
        <tbody id="layoutTableTemplate" runat="server"
              style="height:470px;overflow:scroll;overflow-x:hidden;"></tbody>
        </table>
        </div>
    </LayoutTemplate>

    <ItemTemplate>
      <tr style="height:0px;">
          <td valign="top"><%# Eval("Sku") %> </td>
          <td valign="top"><%# Eval("Abstract")  %></td>
      </tr>
    </ItemTemplate>

</asp:ListView> 



请注意一下上面的布局模板,特别是其中的<TBODY />部分。 ItemTemplate会将其内生成的详细内容插入到<TBODY />之中。


增加分页功能
如果你想为ListView增加分页功能的话,那么就需要使用DataPager控件了。这个分页控件是一个独立的控件,你可以把它放到页面的任何位置,然后使其联到你的ListView控件就可以完成分页的工作了。该分页控件所呈现出来的HTML标记为内联(Inline)元素,所以如果你想精确地设置其位置的话,可以参考下面的代码,为其包裹一个<div />标记。

你可以像下面这样设置分页控件,并可以把其放到页面的任何位置。

<div class="blockheader" style="padding:10px;text-align: right;">
    <asp:DataPager ID="Pager" runat="server" 
                  PagedControlID="lvItems" PageSize="5" >                     
        <Fields>
            <asp:numericpagerfield ButtonCount="10" NextPageText=""
                PreviousPageText="" />
            <asp:nextpreviouspagerfield FirstPageText="First" LastPageText="Last"
                NextPageText="Next" PreviousPageText="Previous" />
        </Fields>
    </asp:DataPager>
</div>



通过上面的代码你会发现,我们可以通过设置DataPager控件的Fields,从而达到手动设置分页布局的目的。 另外还有一个关键点,就是DataPager控件的PagedControlID属性,你需要把它设置为ListView的ID。

当然你也可以把DataPager控件放到布局模板内。

把分页功能作为一个单独的控件分离出来是一个非常好的注意 – 它会让我们有更多的布局和 显示上的自由度。 但是,目前的分页控件还是有其局限性的。它只能结合ListView控件一起工作 – 如果能用在Repeater或GridView上就更好了。另外,它也是要依赖于ViewState的。

还有,现在的DataPager控件没有分页事件,也没有SelectedPageIndex属性。

还有一点需要注意的是,ListView没有内置排序功能。


在ListView中添加和编辑数据
ListView通过EditItemTemplate和InsertItemTemplate来提供编辑数据和添加数据的功能。 这个功能的使用非常类似于GridView的编辑特性的使用,只不过它用的都是自定义模板。

<asp:ListView ID="lvItems" runat="server"
              DataSourceID="Data"
              ItemContainerID="layoutTemplate"
              DataKeyNames="Pk"
              InsertItemPosition="None"             
>

    <Layouttemplate>               
        <div id="layoutTemplate" runat="server" />                       
    </Layouttemplate>       
       
    <ItemTemplate>
        <div class="itemdisplay">
        <b><%# Eval("Sku") %></b><br />
        <%# Eval("Abstract") %></div>
       
        <asp:Button ID="Button1" runat="server" CommandName="Edit" Text="Edit" />
        <asp:Button ID="Button2" runat="server" CommandName="Delete" Text="Delete" />
    </ItemTemplate>
    <AlternatingItemTemplate >
        <div class="itemdisplayalternate">
        <b><%# Eval("Sku") %></b><br />
        <%# Eval("Abstract") %></div>
        <asp:Button ID="Button1" runat="server" CommandName="Edit" Text="Edit" />
        <asp:Button ID="Button2" runat="server" CommandName="Delete" Text="Delete" />
    </AlternatingItemTemplate>
    <EditItemTemplate>
        <div class="gridalternate">
        Sku: <asp:TextBox runat="server" ID="txtSku" Text='<%# Bind("Sku") %>'></asp:TextBox>
        <br />
        Abstract: <asp:TextBox  runat="server" id="txtAbstract" Text='<%# Bind("Abstract") %>'></asp:TextBox>
        <br />
        <asp:Button ID="Button3" runat="server" CommandName="Update" Text="Update" />
        <asp:Button ID="Button4" runat="server"
                    CommandName="Cancel" Text="Cancel" /><br />
        </div>
    </EditItemTemplate>
    <InsertItemTemplate>
        <div style="background:Yellow">
        <asp:TextBox runat="server" ID="txtSku" Text='<%# Bind("Sku") %>'></asp:TextBox>
        <br />
        <asp:TextBox  runat="server" id="txtAbstract" Text='<%# Bind("Abstract") %>'></asp:TextBox>
        <br />
        </div>
        <asp:Button ID="Button3" runat="server" CommandName="Inser" Text="Insert" />
        <asp:Button ID="Button4" runat="server"
                    CommandName="Cancel" Text="Cancel" /><br />
    </InsertItemTemplate>           
</asp:ListView>



在本例中我使用的是SqlDataSource(我比较懒),SqlDataSource中的Insert和Update语句是你必须要提供的。 InsertItemTemplate是ListView中新增的非常受欢迎的模板,我们可以把它的UI设置成与编辑模板相一致。我们还可以通过InsertItemPosition属性来指定插入模板的位置,它可以是FirstItem、LastItem或None。一般来说,应该把它设置为None,然后通过某个按钮来设置插入模板的显示位置(FirstItem或LastItem)。示例代码如下:

protected void btnAddItem_Click(object sender, EventArgs e)
{
    this.lvItems.InsertItemPosition = InsertItemPosition.FirstItem;
}

protected void lvItems_ItemCommand(object sender, ListViewCommandEventArgs e)
{
    if (e.CommandName == "Update")
    {
        TextBox tb = e.Item.FindControl("txtSku") as TextBox;
        this.lvItems.InsertItemPosition = InsertItemPosition.None;
        Response.Write(tb.Text);
    }
    if (e.CommandName == "Cancel")
    {
        this.lvItems.InsertItemPosition = InsertItemPosition.None;
    } 
   
}



你可以在OnItemCommand中写上自己的逻辑,使得一旦执行了Update或Cancel命令就设置InsertItemPosition为None。


分组
大概介绍一下,最后生成的HTML代码会先用GroupTemplate分组,然后再以LayoutTemplate做容器包裹起来。
  <Layouttemplate>               
        <div id="groupContainer" runat="server" >                               
        </div>
    </Layouttemplate>
    <GroupTemplate>       
        <div class="blockheader" style="height:23px;padding:7px">Group Header:</div>
        <div id="layoutTemplate" runat="server" />                       
    </GroupTemplate>
你可以设置ListView的GroupItemCount属性,来指定每组显示多少条记录。


总结
ListView 是ASP.NET中新增的一个非常酷的控件。在本文中我已经介绍过了,相对于GridView来说它有着更为丰富的布局手段,你可以在它的模板内写任何HTML标记或者控件。如果你使用过Repeater和GridView的话,那么你将会轻松的上手ListView,不过很明显地,你也将要手写更多的HTML标记。但是,它也将会给我们带来更多的布局上的自由度,同时也具有编辑、插入等特性。 这就是ASP.NET 3.5给我们带来的非常棒的控件。

转载于:https://www.cnblogs.com/kingjiong/archive/2008/09/01/1281076.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值