DataGrid Web 服务器控件声明性语法
更新:2007 年 11 月
DataGrid 控件呈现表格式数据绑定网格。该控件允许您定义各种类型的列,这些列有的用于控制网格的单元格内容的布局,如绑定列和模板列;有的用于添加特定功能,如编辑按钮列和超级链接列等。该控件还支持各种用于在数据中进行分页的选项。
<asp:DataGrid
AccessKey="string"
AllowCustomPaging="True|False"
AllowPaging="True|False"
AllowSorting="True|False"
AutoGenerateColumns="True|False"
BackColor="color name|#dddddd"
BackImageUrl="uri"
BorderColor="color name|#dddddd"
BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge|
Inset|Outset"
BorderWidth="size"
Caption="string"
CaptionAlign="NotSet|Top|Bottom|Left|Right"
CellPadding="integer"
CellSpacing="integer"
CssClass="string"
DataKeyField="string"
DataMember="string"
DataSource="string"
DataSourceID="string"
EditItemIndex="integer"
Enabled="True|False"
EnableTheming="True|False"
EnableViewState="True|False"
Font-Bold="True|False"
Font-Italic="True|False"
Font-Names="string"
Font-Overline="True|False"
Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|Medium|
Large|X-Large|XX-Large"
Font-Strikeout="True|False"
Font-Underline="True|False"
ForeColor="color name|#dddddd"
GridLines="None|Horizontal|Vertical|Both"
Height="size"
HorizontalAlign="NotSet|Left|Center|Right|Justify"
ID="string"
OnCancelCommand="CancelCommand event handler"
OnDataBinding="DataBinding event handler"
OnDeleteCommand="DeleteCommand event handler"
OnDisposed="Disposed event handler"
OnEditCommand="EditCommand event handler"
OnInit="Init event handler"
OnItemCommand="ItemCommand event handler"
OnItemCreated="ItemCreated event handler"
OnItemDataBound="ItemDataBound event handler"
OnLoad="Load event handler"
OnPageIndexChanged="PageIndexChanged event handler"
OnPreRender="PreRender event handler"
OnSelectedIndexChanged="SelectedIndexChanged event handler"
OnSortCommand="SortCommand event handler"
OnUnload="Unload event handler"
OnUpdateCommand="UpdateCommand event handler"
PageSize="integer"
runat="server"
SelectedIndex="integer"
ShowFooter="True|False"
ShowHeader="True|False"
SkinID="string"
Style="string"
TabIndex="integer"
ToolTip="string"
UseAccessibleHeader="True|False"
Visible="True|False"
Width="size"
>
<AlternatingItemStyle />
<Columns>
<asp:BoundColumn
DataField="string"
DataFormatString="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
ReadOnly="True|False"
SortExpression="string"
Visible="True|False"
>
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:BoundColumn>
<asp:ButtonColumn
ButtonType="LinkButton|PushButton"
CausesValidation="True|False"
CommandName="string"
DataTextField="string"
DataTextFormatString="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
SortExpression="string"
Text="string"
ValidationGroup="string"
Visible="True|False"
>
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:ButtonColumn>
<asp:EditCommandColumn
ButtonType="LinkButton|PushButton"
CancelText="string"
CausesValidation="True|False"
EditText="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
SortExpression="string"
UpdateText="string"
ValidationGroup="string"
Visible="True|False"
>
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:EditCommandColumn>
<asp:HyperLinkColumn
DatahrefField="string"
DatahrefFormatString="string"
DataTextField="string"
DataTextFormatString="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
href="uri"
SortExpression="string"
Target="string|_blank|_parent|_search|_self|_top"
Text="string"
Visible="True|False"
>
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:HyperLinkColumn>
<asp:TemplateColumn
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
SortExpression="string"
Visible="True|False"
>
<FooterStyle />
<HeaderStyle />
<ItemStyle />
<EditItemTemplate>
<!-- child controls -->
</EditItemTemplate>
<FooterTemplate>
<!-- child controls -->
</FooterTemplate>
<HeaderTemplate>
<!-- child controls -->
</HeaderTemplate>
<ItemTemplate>
<!-- child controls -->
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<EditItemStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
<PagerStyle
BackColor="color name|#dddddd"
BorderColor="color name|#dddddd"
BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|
Groove|Ridge|Inset|Outset"
BorderWidth="size"
CssClass="string"
Font-Bold="True|False"
Font-Italic="True|False"
Font-Names="string"
Font-Overline="True|False"
Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|
Medium|Large|X-Large|XX-Large"
Font-Strikeout="True|False"
Font-Underline="True|False"
ForeColor="color name|#dddddd"
Height="size"
HorizontalAlign="NotSet|Left|Center|Right|Justify"
Mode="NextPrev|NumericPages"
NextPageText="string"
OnDisposed="Disposed event handler"
PageButtonCount="integer"
Position="Bottom|Top|TopAndBottom"
PrevPageText="string"
VerticalAlign="NotSet|Top|Middle|Bottom"
Visible="True|False"
Width="size"
Wrap="True|False"
/>
<SelectedItemStyle />
</asp:DataGrid>
备注
在使用 DataGrid 控件前,请考虑改用 GridView 控件。GridView 控件是 .NET Framework 2.0 版中的新控件,并且是 DataGrid 控件的后继控件。
DataGrid 控件将数据源的字段显示为表中的列。DataGrid 控件中的每一行表示数据源中的一个记录。DataGrid 控件支持选择、编辑、删除、分页和排序。
默认情况下,AutoGenerateColumns 属性设置为 true,这将为数据源中的每一个字段创建一个 BoundColumn 对象。然后,每一个字段按照在数据源中出现的顺序在 DataGrid 控件中呈现为一个列。
还可以通过将 AutoGenerateColumns 属性设置为 false,然后列出希望包含在开始和结束 <Columns> 标记之间的列来手动控制在 DataGrid 控件中显示的列。指定的列按列出的顺序添加到 Columns 集合中。这使您可以通过编程方式控制 DataGrid 控件中的列。
![]() |
---|
DataGrid 控件中的列的显示顺序取决于这些列在 Columns 集合中的出现顺序。尽管可以通过操作 Columns 集合以编程方式更改列的顺序,但按所需的显示顺序列出这些列会更为容易。 |
![]() |
---|
显式声明的列可以与自动生成的列一起使用。当同时使用这二者时,首先呈现的是显式声明的列,其后是自动生成的列。自动生成的列不会添加到 Columns 集合中。 |
不同的列类型确定控件中列的行为。DataGrid 控件允许您使用以下列类型。
列类型 |
说明 |
---|---|
将最常用的编辑命令(Edit、Update、Cancel)封装在预定义的列类型中。 |
|
创建一个列,该列具有一组绑定到数据字段值的超级链接。例如,一个显示订单列表的网格可以包含一个超链接列,OrderID 字段在该列中呈现为一个指向显示该订单详细信息的页的超链接。 |
|
创建一个列,该列绑定到数据源中的一个字段并使用样式呈现在表单元格中。这是 DataGrid 控件的默认列类型。 |
|
创建一个列,该列针对列中的每一项包含一个用户定义的命令按钮(如 Add 或 Remove)。 |
|
创建一个列,该列允许您使用自定义 HTML 元素和控件的模板定义控件的布局。 |
下表提供有关可以为 DataGrid 控件声明的列的信息。
DataGridColumn 基本属性
以下属性是所有 DataGrid 列类型都具有的属性。
属性 |
说明 |
---|---|
显示在列的下边缘的文本。 |
|
代替列标头中的 HeaderText 文本而呈现的图像的 URL。 |
|
显示在列的上边缘的文本。 |
|
一个对绑定列所属的 DataGrid 控件的引用(只读)。 该属性仅在编程时使用。 |
|
当用户指定按该列的内容进行排序时,对数据源进行排序时所依据的字段的名称。 |
|
如果显示列,则为 true;否则为 false。 |
BoundColumn 属性
属性 |
说明 |
---|---|
DataSource 中作为该列的数据源的对象的字段或属性。 |
|
指定字段在单元格中如何显示的格式设置表达式字符串。它类似于由 Format 方法使用的格式设置表达式。 |
|
如果将行置于编辑模式时无法编辑列,则为 true;否则为 false。 |
ButtonColumn 属性
属性 |
说明 |
---|---|
要呈现的按钮的类型。默认值为 LinkButton。 编程时,使用 ButtonColumnType 设置此属性。 |
|
一个字符串,它指示在单击列中的某个按钮时发送的命令。此字符串可通过 e事件参数对象的 CommandSource 属性用于事件处理方法中。 DataGrid 控件识别某些标准命令名。这些命令名包括 Select、Sort、Update、Cancel、Edit、Delete 和 Page。 |
|
源自 DataSource 的字段名,它绑定到 ButtonColumn 中按钮的 Text 属性。 |
|
指定字段在单元格中如何显示的格式设置表达式字符串。 |
|
在此列中的按钮表面上显示的标题。如果设置了 DataTextField,则它将重写此值。 |
TemplateColumn 属性
属性 |
说明 |
---|---|
当列处于编辑模式时定义该列的 HTML 元素和控件。 |
|
定义列脚注的 HTML 元素和控件。 |
|
定义列标头的 HTML 元素和控件。 |
|
在显示列时定义该列的 HTML 元素和控件。 |
HyperLinkColumn 属性
属性 |
说明 |
---|---|
DatahrefField |
DataSource 中对象的字段或属性,它提供要移动到的页的 URL。 |
DatahrefFormatString |
用于 Text 属性的格式表达式。 |
DataSource 中作为该列的 Text 属性的数据源的对象的字段或属性。 |
|
格式设置字符串,它指定 Text 属性在控件中的显示方式。 |
|
href |
要移动到的页的 URL。如果设置了 DatahrefField,则它将重写此属性。 |
用于显示页的目标窗口。它可以是窗口或框架引用的名称,如 _TOP。 |
|
超级链接的文本。 |
EditCommandColumn 属性
属性 |
说明 |
---|---|
要呈现的按钮的类型。默认值为 LinkButton。 编程时,使用 ButtonColumnType 设置此属性。 |
|
在 Edit 按钮的表面上显示的字符串。 |
|
在 Update 按钮的表面上显示的字符串。 |
|
在 Cancel 按钮的表面上显示的字符串。 |
通过设置 DataGrid控件的不同部分的样式属性,可以自定义该控件的外观。下表列出 DataGrid 控件的不同部分的样式属性。
样式属性
样式属性 |
说明 |
Style 类 |
---|---|---|
隔项(交替项)的样式。 |
||
正在编辑的项的样式。 |
||
列表结尾处的脚注(如果有的话)的样式。 |
||
列表开始处的标头(如果有的话)的样式。 |
||
单个项的样式。 |
||
页选择控件的样式。 |
||
当前选定项的样式。 |
有关每个样式类支持的属性的信息,请参见样式对象属性。
DataGrid 控件包含以页段为单位显示其内容的内置功能。页上的项数由 PageSize 属性确定。如果没有为 PageSize 属性指定任何值,则 DataGrid 控件在该页上一次显示十个项。
默认情况下,禁用分页。若要启用分页,请将 AllowPaging 属性设置为 true 并提供处理 PageIndexChanged 事件的代码。PageIndexChanged 事件的典型逻辑是将 CurrentPageIndex 属性设置为要显示页的索引,然后将数据源重新绑定到该控件。要显示的页的索引通常是通过传递给事件处理程序的 DataGridPageChangedEventArgs 对象的 NewPageIndex 属性来访问的。
对于标准分页,DataGrid 控件假定数据源包含所有要显示的项。DataGrid 控件根据页索引(由 CurrentPageIndex 属性指定)以及该页上的项数(由 PageSize 属性指定)计算当前页上的项的索引。
还可通过编程方式向由 DataGrid 控件生成的 <td> 和 <tr> 标记添加属性来进一步自定义 DataGrid 控件的外观。通过为 ItemCreated 或 ItemDataBound 事件提供自定义事件处理程序,可将属性插入到标记中。通常情况下,属性被添加到 ItemCreated 事件的事件处理程序中。但如果属性依赖于实际数据,则将属性添加到 ItemDataBound 事件的处理程序中。
若要将属性添加到 <td> 标记,请首先获取表示要向其添加该属性的 DataGrid 控件中单元格的 TableCell 对象。可使用传递到事件处理程序中的 DataGridItemEventArgs 的 Item 属性(DataGridItemEventArgs 索引器)的 Control.Controls 集合获取所需的 TableCell。然后可以使用 TableCell 的 Attributes 集合的 AttributeCollection.Add 方法,将属性添加到 <td> 标记。
若要将属性添加到 <tr> 标记,请首先获取表示要向其添加该属性的 DataGrid 控件中行的 DataGridItem。可使用传递到事件处理程序中的 DataGridItemEventArgs 的 Item 属性(DataGridItemEventArgs 索引器)获取所需的 DataGridItem。然后可以使用 DataGridItem 的 Attributes 集合的 AttributeCollection.Add 方法,将属性添加到 <tr> 标记。
![]() |
---|
文本在 DataGrid 控件中显示之前并非 HTML 编码形式。这使得可以在文本中的 HTML 标记中嵌入脚本。如果控件的值是由用户输入的,请务必要对输入值进行验证以防止出现安全漏洞。 |
有关 DataGrid Web 服务器控件的属性和事件的详细信息,请参见 DataGrid 类文档。
示例
下面的示例演示如何使用 DataGrid 控件显示数据源中的项。
<%@ Page Language="VB" 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 xmlns="http://www.w3.org/1999/xhtml" >
<script language="VB" runat="server">
Function CreateDataSource() As ICollection
Dim dt As New DataTable()
Dim dr As DataRow
dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))
Dim i As Integer
For i = 0 To 8
dr = dt.NewRow()
dr(0) = i
dr(1) = "Item " + i.ToString()
dr(2) = 1.23 *(i + 1)
dt.Rows.Add(dr)
Next i
Dim dv As New DataView(dt)
Return dv
End Function 'CreateDataSource
Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then
' Load this data only once.
ItemsGrid.DataSource = CreateDataSource()
ItemsGrid.DataBind()
End If
End Sub 'Page_Load
</script>
<head runat="server">
<title>DataGrid Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>DataGrid Example</h3>
<b>Product List</b>
<asp:DataGrid id="ItemsGrid"
BorderColor="black"
BorderWidth="1"
CellPadding="3"
AutoGenerateColumns="true"
runat="server">
<HeaderStyle BackColor="#00aaaa">
</HeaderStyle>
</asp:DataGrid>
</form>
</body>
</html>
<%@ 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 xmlns="http://www.w3.org/1999/xhtml" >
<script language="C#" runat="server">
ICollection CreateDataSource()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
for (int i = 0; i < 9; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Item " + i.ToString();
dr[2] = 1.23 * (i + 1);
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}
void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
// Load this data only once.
ItemsGrid.DataSource= CreateDataSource();
ItemsGrid.DataBind();
}
}
</script>
<head runat="server">
<title>DataGrid Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>DataGrid Example</h3>
<b>Product List</b>
<asp:DataGrid id="ItemsGrid"
BorderColor="black"
BorderWidth="1"
CellPadding="3"
AutoGenerateColumns="true"
runat="server">
<HeaderStyle BackColor="#00aaaa">
</HeaderStyle>
</asp:DataGrid>
</form>
</body>
</html>
下面的示例演示如何在 DataGrid 控件中使用分页。
<%@ Page Language="VB" 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 xmlns="http://www.w3.org/1999/xhtml" >
<script language="VB" runat="server">
Dim Cart As DataTable
Dim CartView As DAtaView
Function CreateDataSource() As ICollection
Dim dt As New DataTable()
Dim dr As DataRow
dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))
Dim i As Integer
For i = 0 To 99
dr = dt.NewRow()
dr(0) = i
dr(1) = "Item " + i.ToString()
dr(2) = 1.23 *(i + 1)
dt.Rows.Add(dr)
Next i
Dim dv As New DataView(dt)
Return dv
End Function 'CreateDataSource
Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then
' Need to load this data only once.
ItemsGrid.DataSource = CreateDataSource()
ItemsGrid.DataBind()
End If
If CheckBox1.Checked Then
ItemsGrid.PagerStyle.Mode = PagerMode.NumericPages
Else
ItemsGrid.PagerStyle.Mode = PagerMode.NextPrev
End If
End Sub 'Page_Load
Sub Grid_Change(sender As Object, e As DataGridPageChangedEventArgs)
' Set CurrentPageIndex to the page the user clicked.
ItemsGrid.CurrentPageIndex = e.NewPageIndex
' Rebind the data.
ItemsGrid.DataSource = CreateDataSource()
ItemsGrid.DataBind()
End Sub 'Grid_Change
</script>
<head runat="server">
<title>DataGrid Paging Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>DataGrid Paging Example</h3>
<asp:DataGrid id="ItemsGrid" runat="server"
BorderColor="black"
BorderWidth="1"
CellPadding="3"
AllowPaging="true"
AutoGenerateColumns="false"
OnPageIndexChanged="Grid_Change">
<HeaderStyle BackColor="#00aaaa">
</HeaderStyle>
<PagerStyle Mode="NextPrev">
</PagerStyle>
<Columns>
<asp:BoundColumn
HeaderText="Number"
DataField="IntegerValue"/>
<asp:BoundColumn
HeaderText="Item"
DataField="StringValue"/>
<asp:BoundColumn
HeaderText="Price"
DataField="CurrencyValue"
DataFormatString="{0:c}">
<ItemStyle HorizontalAlign="right">
</ItemStyle>
</asp:BoundColumn>
</Columns>
</asp:DataGrid>
<br />
<asp:CheckBox id="CheckBox1"
Text="Show page navigation"
AutoPostBack="true"
runat="server"/>
</form>
</body>
</html>
<%@ 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 xmlns="http://www.w3.org/1999/xhtml" >
<script language="C#" runat="server">
DataTable Cart;
DataView CartView;
ICollection CreateDataSource()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
for (int i = 0; i < 100; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Item " + i.ToString();
dr[2] = 1.23 * (i+1);
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}
void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
// Need to load this data only once.
ItemsGrid.DataSource = CreateDataSource();
ItemsGrid.DataBind();
}
if (CheckBox1.Checked)
ItemsGrid.PagerStyle.Mode = PagerMode.NumericPages;
else
ItemsGrid.PagerStyle.Mode = PagerMode.NextPrev;
}
void Grid_Change(Object sender, DataGridPageChangedEventArgs e)
{
// Set CurrentPageIndex to the page the user clicked.
ItemsGrid.CurrentPageIndex = e.NewPageIndex;
// Rebind the data.
ItemsGrid.DataSource = CreateDataSource();
ItemsGrid.DataBind();
}
</script>
<head runat="server">
<title>DataGrid Paging Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>DataGrid Paging Example</h3>
<asp:DataGrid id="ItemsGrid" runat="server"
BorderColor="black"
BorderWidth="1"
CellPadding="3"
AllowPaging="true"
AutoGenerateColumns="false"
OnPageIndexChanged="Grid_Change">
<HeaderStyle BackColor="#00aaaa">
</HeaderStyle>
<PagerStyle Mode="NextPrev">
</PagerStyle>
<Columns>
<asp:BoundColumn
HeaderText="Number"
DataField="IntegerValue"/>
<asp:BoundColumn
HeaderText="Item"
DataField="StringValue"/>
<asp:BoundColumn
HeaderText="Price"
DataField="CurrencyValue"
DataFormatString="{0:c}">
<ItemStyle HorizontalAlign="right">
</ItemStyle>
</asp:BoundColumn>
</Columns>
</asp:DataGrid>
<br />
<asp:CheckBox id="CheckBox1"
Text="Show page navigation"
AutoPostBack="true"
runat="server"/>
</form>
</body>
</html>
<%@ Page Language="JScript" 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 xmlns="http://www.w3.org/1999/xhtml" >
<script language="JScript" runat="server">
var Cart : DataTable;
var CartView : DataView;
function CreateDataSource () : ICollection
{
var dt : DataTable = new DataTable();
var dr : DataRow;
dt.Columns.Add(new DataColumn("IntegerValue", Int32));
dt.Columns.Add(new DataColumn("StringValue", System.String));
dt.Columns.Add(new DataColumn("CurrencyValue", double));
for (var i : int = 0; i < 100; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Item " + i.ToString();
dr[2] = 1.23 * (i+1);
dt.Rows.Add(dr);
}
var dv : DataView = new DataView(dt);
return dv;
}
function Page_Load(sender, e : EventArgs)
{
if (!IsPostBack)
{
// Need to load this data only once.
ItemsGrid.DataSource = CreateDataSource();
ItemsGrid.DataBind();
}
if (CheckBox1.Checked)
ItemsGrid.PagerStyle.Mode = PagerMode.NumericPages;
else
ItemsGrid.PagerStyle.Mode = PagerMode.NextPrev;
}
function Grid_Change(sender, e : DataGridPageChangedEventArgs)
{
// Set CurrentPageIndex to the page the user clicked.
ItemsGrid.CurrentPageIndex = e.NewPageIndex;
// Rebind the data.
ItemsGrid.DataSource = CreateDataSource();
ItemsGrid.DataBind();
}
</script>
<head runat="server">
<title>DataGrid Paging Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>DataGrid Paging Example</h3>
<asp:DataGrid id="ItemsGrid" runat="server"
BorderColor="black"
BorderWidth="1"
CellPadding="3"
AllowPaging="true"
AutoGenerateColumns="false"
OnPageIndexChanged="Grid_Change">
<HeaderStyle BackColor="#00aaaa">
</HeaderStyle>
<PagerStyle Mode="NextPrev">
</PagerStyle>
<Columns>
<asp:BoundColumn
HeaderText="Number"
DataField="IntegerValue"/>
<asp:BoundColumn
HeaderText="Item"
DataField="StringValue"/>
<asp:BoundColumn
HeaderText="Price"
DataField="CurrencyValue"
DataFormatString="{0:c}">
<ItemStyle HorizontalAlign="right">
</ItemStyle>
</asp:BoundColumn>
</Columns>
</asp:DataGrid>
<br />
<asp:CheckBox id="CheckBox1"
Text="Show page navigation"
AutoPostBack="true"
runat="server"/>
</form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Function CreateDataSource() As ICollection
' Create sample data for the DataGrid control.
Dim dt As DataTable = New DataTable()
Dim dr As DataRow
' Define the columns of the table.
dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))
' Populate the table with sample values.
Dim i As Integer
For i = 0 To 100
dr = dt.NewRow()
dr(0) = i
dr(1) = "Item " & i.ToString()
dr(2) = 1.23 * (i + 1)
dt.Rows.Add(dr)
Next i
Dim dv As DataView = New DataView(dt)
Return dv
End Function
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
' Load sample data only once, when the page is first loaded.
If Not IsPostBack Then
ItemsGrid.DataSource = CreateDataSource()
ItemsGrid.DataBind()
End If
End Sub
Sub Check_Change(ByVal sender As Object, ByVal e As EventArgs)
' Allow or prevent paging depending on the user's selection.
ItemsGrid.AllowPaging = AllowPagingCheckBox.Checked()
' Rebind the data to refresh the DataGrid control.
ItemsGrid.DataSource = CreateDataSource()
ItemsGrid.DataBind()
End Sub
Sub Grid_Change(ByVal sender As Object, ByVal e As DataGridPageChangedEventArgs)
' For the DataGrid control to navigate to the correct page when
' paging is allowed, the CurrentPageIndex property must be updated
' programmatically. This process is usually accomplished in the
' event-handling method for the PageIndexChanged event.
' Set CurrentPageIndex to the page the user clicked.
ItemsGrid.CurrentPageIndex = e.NewPageIndex
' Rebind the data to refresh the DataGrid control.
ItemsGrid.DataSource = CreateDataSource()
ItemsGrid.DataBind()
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head2" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>DataGrid AllowPaging Example</h3>
<p>Select whether to allow paging in the DataGrid control.<br />
<asp:CheckBox id="AllowPagingCheckBox"
Text="Allow paging"
AutoPostBack="True"
Checked="True"
OnCheckedChanged="Check_Change"
runat="server" />
</p>
<hr />
<asp:Label ID="Label1" runat="server"
AssociatedControlID="ItemsGrid"
Font-Bold="true">Product List</asp:Label>
<asp:DataGrid id="ItemsGrid" runat="server"
BorderColor="Gray"
BorderWidth="1"
CellPadding="3"
UseAccessibleHeader="true"
AutoGenerateColumns="False"
PageSize="10"
AllowPaging="True"
OnPageIndexChanged="Grid_Change">
<HeaderStyle BackColor="LightBlue" />
<Columns>
<asp:BoundColumn DataField="IntegerValue"
SortExpression="IntegerValue"
ItemStyle-HorizontalAlign="center"
HeaderText="Item" />
<asp:BoundColumn DataField="StringValue"
HeaderText="Description"
ItemStyle-HorizontalAlign="left"
SortExpression="StringValue" />
<asp:BoundColumn DataField="CurrencyValue"
HeaderText="Price"
SortExpression="CurrencyValue"
DataFormatString="{0:c}" />
</Columns>
<ItemStyle HorizontalAlign="Right" />
</asp:DataGrid>
</div>
</form>
</body>
</html>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
private ICollection CreateDataSource()
{
// Create sample data for the DataGrid 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)));
// Populate the table with sample values.
for (int i = 0; i <= 100; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Item " + i.ToString();
dr[2] = 1.23 * (i + 1);
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}
private void Page_Load(Object sender, EventArgs e)
{
// Load sample data only once, when the page is first loaded.
if (!IsPostBack)
{
ItemsGrid.DataSource = CreateDataSource();
ItemsGrid.DataBind();
}
}
private void Check_Change(Object sender, EventArgs e)
{
// Allow or prevent paging depending
// on the user's selection.
ItemsGrid.AllowPaging = AllowPagingCheckBox.Checked;
// Rebind the data to refresh the DataGrid control.
ItemsGrid.DataSource = CreateDataSource();
ItemsGrid.DataBind();
}
private void Grid_Change(Object sender, DataGridPageChangedEventArgs e)
{
// For the DataGrid control to navigate to the correct page when
// paging is allowed, the CurrentPageIndex property must be updated
// programmatically. This process is usually accomplished in the
// event-handling method for the PageIndexChanged event.
// Set CurrentPageIndex to the page the user clicked.
ItemsGrid.CurrentPageIndex = e.NewPageIndex;
// Rebind the data to refresh the DataGrid control.
ItemsGrid.DataSource = CreateDataSource();
ItemsGrid.DataBind();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>DataGrid AllowPaging Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>DataGrid AllowPaging Example</h3>
<p>Select whether to allow paging in the DataGrid control.<br />
<asp:CheckBox id="AllowPagingCheckBox"
Text="Allow paging"
AutoPostBack="True"
Checked="True"
OnCheckedChanged="Check_Change"
runat="server" />
</p>
<hr />
<asp:Label runat="server"
AssociatedControlID="ItemsGrid"
Font-Bold="true">Product List</asp:Label>
<asp:DataGrid id="ItemsGrid" runat="server"
BorderColor="Gray"
BorderWidth="1"
CellPadding="3"
AutoGenerateColumns="False"
UseAccessibleHeader="true"
PageSize="10"
AllowPaging="True"
OnPageIndexChanged="Grid_Change">
<HeaderStyle BackColor="LightBlue" />
<Columns>
<asp:BoundColumn DataField="IntegerValue"
SortExpression="IntegerValue"
ItemStyle-HorizontalAlign="center"
HeaderText="Item" />
<asp:BoundColumn DataField="StringValue"
HeaderText="Description"
ItemStyle-HorizontalAlign="left"
SortExpression="StringValue" />
<asp:BoundColumn DataField="CurrencyValue"
HeaderText="Price"
SortExpression="CurrencyValue"
DataFormatString="{0:c}" />
</Columns>
<ItemStyle HorizontalAlign="Right" />
</asp:DataGrid>
</div>
</form>
</body>
</html>
通常情况下,每当 DataGrid 控件显示一页信息时,就加载包含列表中所有项的数据源。如果数据源非常大,这可能会耗费大量资源。自定义分页使您可以只加载显示该页所需的数据段。
若要启用自定义分页,请将 AllowPaging 属性和 AllowCustomPaging 属性设置为 true,并提供处理 PageIndexChanged 事件的代码。PageIndexChanged 事件的典型逻辑是将 CurrentPageIndex 属性设置为要显示页的索引,然后将数据源重新绑定到该控件。要显示的页的索引通常是通过传递给事件处理程序的 DataGridPageChangedEventArgs 对象的 NewPageIndex 属性来访问的。然后,创建包含要在单个页上显示的数据的数据源。创建数据源后,使用 DataBind 方法将数据源绑定到 DataGrid 控件。由于只加载了一个数据段,因此将 VirtualItemCount 属性设置为要在 DataGrid 控件中显示的项的总数。这使控件可以确定分页控件所需的总页数。
使用自定义分页时,DataGrid 控件假定数据源只包含要在当前页上显示的项。数据源中数量等于由 PageSize 属性指定的项数的所有项都被显示出来。
下面的代码示例演示如何使用 AllowCustomPaging 属性启用自定义分页。
<%@ Page Language="VB" 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 xmlns="http://www.w3.org/1999/xhtml" >
<script runat="server">
' Normally, an entire data source is loaded in the DataGrid control,
' which can take up a lot of resources. This example uses custom
' paging, which loads only the segment of data needed to fill a
' single page. In order to query for the appropriate segment of
' data, the index of the first item displayed on a page must be
' tracked as the user navigates between pages.
Dim startIndex As Integer = 0
Function CreateDataSource() As ICollection
' Create sample data for the DataGrid control.
Dim dt As DataTable = New DataTable()
Dim dr As DataRow
' Define the columns of the table.
dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
dt.Columns.Add(New DataColumn("DateTimeValue", GetType(String)))
dt.Columns.Add(New DataColumn("BoolValue", GetType(Boolean)))
' Populate the table with sample values. When using custom paging,
' a query should only return enough data to fill a single page,
' beginning at the start index.
Dim i As Integer
For i = startIndex To ((startIndex + MyDataGrid.PageSize) - 1)
dr = dt.NewRow()
dr(0) = i
dr(1) = "Item " & i.ToString()
dr(2) = DateTime.Now.ToShortDateString()
If (i Mod 2 <> 0) Then
dr(3) = True
Else
dr(3) = False
End If
dt.Rows.Add(dr)
Next i
Dim dv As DataView = New DataView(dt)
Return dv
End Function
Sub Page_Load(sender As Object, e As EventArgs)
' Load sample data only once, when the page is first loaded.
If Not IsPostBack Then
' Set the virtual item count, which specifies the total number
' items displayed in the DataGrid control when custom paging
' is used.
MyDataGrid.VirtualItemCount = 200
' Retrieve the segment of data to display on the page from the
' data source and bind it to the DataGrid control.
BindGrid()
End If
End Sub
Sub MyDataGrid_Page(sender as Object, e As DataGridPageChangedEventArgs)
' For the DataGrid control to navigate to the correct page when
' paging is allowed, the CurrentPageIndex property must be updated
' programmatically. This process is usually accomplished in the
' event-handling method for the PageIndexChanged event.
' Set CurrentPageIndex to the page the user clicked.
MyDataGrid.CurrentPageIndex = e.NewPageIndex
' Calculate the index of the first item to display on the page
' using the current page index and the page size.
startIndex = MyDataGrid.CurrentPageIndex * MyDataGrid.PageSize
' Retrieve the segment of data to display on the page from the
' data source and bind it to the DataGrid control.
BindGrid()
End Sub
Sub BindGrid()
MyDataGrid.DataSource = CreateDataSource()
MyDataGrid.DataBind()
End Sub
</script>
<head runat="server">
<title> DataGrid Custom Paging Example </title>
</head>
<body>
<form id="form1" runat="server">
<h3> DataGrid Custom Paging Example </h3>
<asp:DataGrid id="MyDataGrid"
AllowCustomPaging="True"
AllowPaging="True"
PageSize="10"
OnPageIndexChanged="MyDataGrid_Page"
runat="server">
<HeaderStyle BackColor="Navy"
ForeColor="White"
Font-Bold="True" />
<PagerStyle Mode="NumericPages"
HorizontalAlign="Right" />
</asp:DataGrid>
</form>
</body>
</html>
<%@ 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 xmlns="http://www.w3.org/1999/xhtml" >
<script runat="server">
// Normally, an entire data source is loaded in the DataGrid control,
// which can take up a lot of resources. This example uses custom
// paging, which loads only the segment of data needed to fill a
// single page. In order to query for the appropriate segment of
// data, the index of the first item displayed on a page must be
// tracked as the user navigates between pages.
int startIndex = 0;
ICollection CreateDataSource()
{
// Create sample data for the DataGrid 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("DateTimeValue", typeof(string)));
dt.Columns.Add(new DataColumn("BoolValue", typeof(bool)));
// Populate the table with sample values. When using custom paging,
// a query should only return enough data to fill a single page,
// beginning at the start index.
for (int i = startIndex; i < (startIndex + MyDataGrid.PageSize); i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Item " + i.ToString();
dr[2] = DateTime.Now.ToShortDateString();
dr[3] = (i % 2 != 0) ? true : false;
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)
{
// Set the virtual item count, which specifies the total number
// items displayed in the DataGrid control when custom paging
// is used.
MyDataGrid.VirtualItemCount = 200;
// Retrieve the segment of data to display on the page from the
// data source and bind it to the DataGrid control.
BindGrid();
}
}
void MyDataGrid_Page(Object sender, DataGridPageChangedEventArgs e)
{
// For the DataGrid control to navigate to the correct page when
// paging is allowed, the CurrentPageIndex property must be updated
// programmatically. This process is usually accomplished in the
// event-handling method for the PageIndexChanged event.
// Set CurrentPageIndex to the page the user clicked.
MyDataGrid.CurrentPageIndex = e.NewPageIndex;
// Calculate the index of the first item to display on the page
// using the current page index and the page size.
startIndex = MyDataGrid.CurrentPageIndex * MyDataGrid.PageSize;
// Retrieve the segment of data to display on the page from the
// data source and bind it to the DataGrid control.
BindGrid();
}
void BindGrid()
{
MyDataGrid.DataSource = CreateDataSource();
MyDataGrid.DataBind();
}
</script>
<head runat="server">
<title> DataGrid Custom Paging Example </title>
</head>
<body>
<form id="form1" runat="server">
<h3> DataGrid Custom Paging Example </h3>
<asp:DataGrid id="MyDataGrid"
AllowCustomPaging="True"
AllowPaging="True"
PageSize="10"
OnPageIndexChanged="MyDataGrid_Page"
runat="server">
<HeaderStyle BackColor="Navy"
ForeColor="White"
Font-Bold="True" />
<PagerStyle Mode="NumericPages"
HorizontalAlign="Right" />
</asp:DataGrid>
</form>
</body>
</html>
DataGrid 控件还提供内置的排序功能。启用排序时,LinkButton 控件即呈现在每一列的标头中,使您可以按选定列对 DataGrid 进行排序。单击 LinkButton 时将引发 SortCommand 事件。提供事件处理程序代码的任务由您来完成。该处理程序的典型逻辑是对列表进行排序,然后将数据重新绑定到 DataGrid。
下面的示例演示如何在 DataGrid 控件中使用排序。
<%@ Page Language="VB" 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 xmlns="http://www.w3.org/1999/xhtml" >
<script language="VB" runat="server">
Dim SortExpression As String
Function CreateDataSource() As ICollection
Dim dt As New DataTable()
Dim dr As DataRow
Dim Rand_Num As New Random()
dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))
Dim i As Integer
For i = 0 To 14
dr = dt.NewRow()
dr(0) = i
dr(1) = "Item " & i.ToString()
dr(2) = 1.23 * Rand_Num.Next(1, 15)
dt.Rows.Add(dr)
Next i
Dim dv As New DataView(dt)
dv.Sort = SortExpression
Return dv
End Function 'CreateDataSource
Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then
If SortExpression = "" Then
SortExpression = "IntegerValue"
End If
ItemsGrid.DataSource = CreateDataSource()
ItemsGrid.DataBind()
End If
End Sub 'Page_Load
Sub Sort_Grid(sender As Object, e As DataGridSortCommandEventArgs)
SortExpression = e.SortExpression.ToString()
ItemsGrid.DataSource = CreateDataSource()
ItemsGrid.DataBind()
End Sub 'Sort_Grid
</script>
<head runat="server">
<title>DataGrid Sorting Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>DataGrid Sorting Example</h3>
<asp:DataGrid id="ItemsGrid" runat="server"
BorderColor="black"
BorderWidth="1"
CellPadding="3"
AllowSorting="true"
OnSortCommand="Sort_Grid"
HeaderStyle-BackColor="#00aaaa"
AutoGenerateColumns="true"/>
</form>
</body>
</html>
<%@ 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 xmlns="http://www.w3.org/1999/xhtml" >
<script language="C#" runat="server">
string SortExpression;
ICollection CreateDataSource()
{
DataTable dt = new DataTable();
DataRow dr;
Random Rand_Num = new Random();
dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
for (int i = 0; i < 15; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Item " + i.ToString();
dr[2] = 1.23 * Rand_Num.Next(1, 15);
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
dv.Sort=SortExpression;
return dv;
}
void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
if (SortExpression == "")
SortExpression = "IntegerValue";
ItemsGrid.DataSource = CreateDataSource();
ItemsGrid.DataBind();
}
}
void Sort_Grid(Object sender, DataGridSortCommandEventArgs e)
{
SortExpression = e.SortExpression.ToString();
ItemsGrid.DataSource = CreateDataSource();
ItemsGrid.DataBind();
}
</script>
<head runat="server">
<title>DataGrid Sorting Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>DataGrid Sorting Example</h3>
<asp:DataGrid id="ItemsGrid" runat="server"
BorderColor="black"
BorderWidth="1"
CellPadding="3"
AllowSorting="true"
OnSortCommand="Sort_Grid"
HeaderStyle-BackColor="#00aaaa"
AutoGenerateColumns="true"/>
</form>
</body>
</html>
<%@ Page Language="JScript" 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 xmlns="http://www.w3.org/1999/xhtml" >
<script language="JScript" runat="server">
var SortExpression : String;
function CreateDataSource () : ICollection
{
var dt : DataTable = new DataTable();
var dr : DataRow;
var Rand_Num : Random = new Random();
dt.Columns.Add(new DataColumn("IntegerValue", Int32));
dt.Columns.Add(new DataColumn("StringValue", System.String));
dt.Columns.Add(new DataColumn("CurrencyValue", double));
for (var i : int = 0; i < 15; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Item " + i.ToString();
dr[2] = 1.23 * Rand_Num.Next(1, 15);
dt.Rows.Add(dr);
}
var dv : DataView = new DataView(dt);
dv.Sort=SortExpression;
return dv;
}
function Page_Load(sender, e : EventArgs)
{
if (!IsPostBack)
{
if (SortExpression == "")
SortExpression = "IntegerValue";
ItemsGrid.DataSource = CreateDataSource();
ItemsGrid.DataBind();
}
}
function Sort_Grid(sender, e : DataGridSortCommandEventArgs)
{
SortExpression = e.SortExpression.ToString();
ItemsGrid.DataSource = CreateDataSource();
ItemsGrid.DataBind();
}
</script>
<head runat="server">
<title>DataGrid Sorting Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>DataGrid Sorting Example</h3>
<asp:DataGrid id="ItemsGrid" runat="server"
BorderColor="black"
BorderWidth="1"
CellPadding="3"
AllowSorting="true"
OnSortCommand="Sort_Grid"
HeaderStyle-BackColor="#00aaaa"
AutoGenerateColumns="true"/>
</form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Function CreateDataSource() As ICollection
' Create a Random object to mix up the order
' of items in the sample data.
Dim randNum As Random = New Random()
' Create sample data for the DataGrid control.
Dim dt As DataTable = New DataTable()
' Define the columns of the table.
dt.Columns.Add( _
New DataColumn("IntegerValue", GetType(Int32)))
dt.Columns.Add( _
New DataColumn("StringValue", GetType(String)))
dt.Columns.Add( _
New DataColumn("CurrencyValue", GetType(Double)))
' Populate the table with sample values.
Dim i As Integer
For i = 0 To 8
Dim dr As DataRow = dt.NewRow()
dr(0) = i
dr(1) = "Item " & randNum.Next(1, 15).ToString()
dr(2) = 1.23 * randNum.Next(1, 15)
dt.Rows.Add(dr)
Next
' Persist the data source between posts to
' the server, in the session state.
Session("Source") = dt
Dim dv As DataView = New DataView(dt)
Return dv
End Function
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
' Load sample data when the page is first loaded.
If Not IsPostBack Then
ItemsGrid.DataSource = CreateDataSource()
ItemsGrid.DataBind()
End If
End Sub
Sub Sort_Grid(ByVal sender As Object, _
ByVal e As DataGridSortCommandEventArgs)
' Retrieve the data source from session state.
Dim dt As DataTable = _
CType(Session("Source"), DataTable)
' Create a DataView from the DataTable.
Dim dv As DataView = New DataView(dt)
' The DataView provides an easy way to
' sort. Simply set the Sort property with
' the name of the field to sort by.
dv.Sort = e.SortExpression
' Rebind the data source and specify that
' it should be sorted by the field specified
' in the SortExpression property.
ItemsGrid.DataSource = dv
ItemsGrid.DataBind()
End Sub
Sub Check_Change(ByVal sender As Object, _
ByVal e As EventArgs)
' Allow or prevent sorting depending
' on the user's selection.
ItemsGrid.AllowSorting = _
AllowSortingCheckBox.Checked
' After changing the property, rebind
' the data to refresh the DataGrid control.
' Retrieve data source from session state.
Dim dt As DataTable = _
CType(Session("Source"), DataTable)
' Create a DataView from the DataTable.
Dim dv As DataView = New DataView(dt)
' Rebind the data source.
ItemsGrid.DataSource = dv
ItemsGrid.DataBind()
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>
ExtractTemplateRows Example
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>DataGrid AllowSorting Example</h3>
<p>Select whether to allow sorting in the DataGrid control.<br />
<asp:CheckBox id="AllowSortingCheckBox"
Text="Allow sorting"
AutoPostBack="True"
Checked="True"
OnCheckedChanged="Check_Change"
runat="server"/></p>
<hr />
<b>Product List</b>
<asp:DataGrid id="ItemsGrid"
BorderColor="black"
BorderWidth="1"
CellPadding="3"
OnSortCommand="Sort_Grid"
UseAccessibleHeader="true"
AutoGenerateColumns="False"
AllowSorting="True"
runat="server">
<HeaderStyle BackColor="#00aaaa" />
<Columns>
<asp:BoundColumn DataField="IntegerValue"
SortExpression="IntegerValue"
HeaderText="Item"/>
<asp:BoundColumn DataField="StringValue"
SortExpression="StringValue"
HeaderText="Description"/>
<asp:BoundColumn DataField="CurrencyValue"
HeaderText="Price"
SortExpression="CurrencyValue"
DataFormatString="{0:c}">
<ItemStyle HorizontalAlign="Right">
</ItemStyle>
</asp:BoundColumn>
</Columns>
</asp:DataGrid>
</div>
</form>
</body>
</html>
<%@ 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">
<script runat="server">
ICollection CreateDataSource()
{
// Create a Random object to mix up the
// order of items in the sample data.
Random randNum = new Random();
// Create sample data for the DataGrid control.
DataTable dt = new DataTable();
// 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)));
// Populate the table with sample values.
for (int i = 0; i <= 8; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i;
dr[1] = "Item " + randNum.Next(1, 15).ToString();
dr[2] = 1.23 * randNum.Next(1, 15);
dt.Rows.Add(dr);
}
// To persist the data source between posts to the server,
// store it in session state.
Session["Source"] = dt;
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)
{
ItemsGrid.DataSource = CreateDataSource();
ItemsGrid.DataBind();
}
}
void Sort_Grid(Object sender, DataGridSortCommandEventArgs e)
{
// Retrieve the data source from session state.
DataTable dt = (DataTable)Session["Source"];
// Create a DataView from the DataTable.
DataView dv = new DataView(dt);
// The DataView provides an easy way to sort. Simply set the
// Sort property with the name of the field to sort by.
dv.Sort = e.SortExpression;
// Rebind the data source and specify that it should be sorted
// by the field specified in the SortExpression property.
ItemsGrid.DataSource = dv;
ItemsGrid.DataBind();
}
void Check_Change(Object sender, EventArgs e)
{
// Allow or prevent sorting depending on the user's selection.
ItemsGrid.AllowSorting = AllowSortingCheckBox.Checked;
// After changing the property, rebind the data to
// refresh the DataGrid control.
// Retrieve the data source from session state.
DataTable dt = (DataTable)Session["Source"];
// Create a DataView from the DataTable.
DataView dv = new DataView(dt);
// Rebind the data source.
ItemsGrid.DataSource = dv;
ItemsGrid.DataBind();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>
ExtractTemplateRows Example
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>DataGrid AllowSorting Example</h3>
<p>Select whether to allow sorting in the DataGrid control.<br />
<asp:CheckBox id="AllowSortingCheckBox"
Text="Allow sorting"
AutoPostBack="True"
Checked="True"
OnCheckedChanged="Check_Change"
runat="server"/></p>
<hr />
<b>Product List</b>
<asp:DataGrid id="ItemsGrid"
BorderColor="black"
BorderWidth="1"
CellPadding="3"
OnSortCommand="Sort_Grid"
UseAccessibleHeader="true"
AutoGenerateColumns="False"
AllowSorting="True"
runat="server">
<HeaderStyle BackColor="#00aaaa" />
<Columns>
<asp:BoundColumn DataField="IntegerValue"
SortExpression="IntegerValue"
HeaderText="Item"/>
<asp:BoundColumn DataField="StringValue"
SortExpression="StringValue"
HeaderText="Description"/>
<asp:BoundColumn DataField="CurrencyValue"
HeaderText="Price"
SortExpression="CurrencyValue"
DataFormatString="{0:c}">
<ItemStyle HorizontalAlign="Right">
</ItemStyle>
</asp:BoundColumn>
</Columns>
</asp:DataGrid>
</div>
</form>
</body>
</html>