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 は DataGrid コントロールの後継コントロールで、.NET Framework Version 2.0 から導入されています。
DataGrid コントロールは、データ ソースのフィールドをテーブル内の列として表示します。DataGrid コントロールの各行は、データ ソース内のレコードを表します。DataGrid コントロールは、選択、編集、削除、ページング、および並べ替えをサポートしています。
既定では、AutoGenerateColumns プロパティは true に設定されていて、データ ソースのフィールドごとに BoundColumn オブジェクトが作成されます。次に、各フィールドが、データ ソース内で出現している順序で DataGrid コントロールの列として表示されます。
DataGrid コントロールに表示される列を手動で制御するには、AutoGenerateColumns プロパティを false に設定し、表示する列のリストを <Columns> の開始タグと終了タグの間に指定します。指定した列は、リストに記述された順序で 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 などがあります。 |
|
ButtonColumn のボタンの Text プロパティにバインドされた DataSource のフィールド名。 |
|
セルでのフィールドの表示方法を指定する書式指定式文字列。 |
|
列のボタンの表面に表示されるキャプション。DataTextField が設定されている場合、この値はオーバーライドされます。 |
TemplateColumn のプロパティ
プロパティ |
説明 |
---|---|
編集モードになっている列を定義する HTML 要素およびコントロール。 |
|
列フッターを定義する HTML 要素およびコントロール。 |
|
列ヘッダーを定義する HTML 要素およびコントロール。 |
|
表示されている列を定義する HTML 要素およびコントロール。 |
HyperLinkColumn のプロパティ
プロパティ |
説明 |
---|---|
DatahrefField |
リンク先ページの URL を提供する、DataSource 内のオブジェクトのフィールドまたはプロパティ。 |
DatahrefFormatString |
Text プロパティと共に使用される書式指定式。 |
列の Text プロパティのデータ ソースである、DataSource 内のオブジェクトのフィールドまたはプロパティ。 |
|
コントロールでの Text プロパティの表示方法を指定する書式指定式文字列。 |
|
href |
リンク先ページの URL。DatahrefField が設定されている場合、このプロパティはオーバーライドされます。 |
ページを表示するターゲット ウィンドウ。ウィンドウまたは _TOP などのフレーム参照の名前を指定できます。 |
|
ハイパーリンクのテキスト。 |
EditCommandColumn のプロパティ
プロパティ |
説明 |
---|---|
表示するボタンの種類。既定値は LinkButton です。 プログラミング時には、ButtonColumnType を使用してこのプロパティを設定します。 |
|
Edit ボタンの表面に表示される文字列を指定します。 |
|
Update ボタンの表面に表示される文字列を指定します。 |
|
Cancel ボタンの表面に表示される文字列を指定します。 |
コントロールのさまざまな部分のスタイル プロパティを設定することによって、DataGrid コントロールの外観をカスタマイズできます。DataGrid コントロールのさまざまな部分に適用できるスタイル プロパティを次の表に一覧表示します。
スタイル プロパティ
スタイル プロパティ |
説明 |
スタイル クラス |
---|---|---|
1 つおきの項目 (交互の項目) のスタイル。 |
||
編集中の項目のスタイル。 |
||
リストの末尾のフッターのスタイル (フッターがある場合)。 |
||
リストの先頭のヘッダーのスタイル (ヘッダーがある場合)。 |
||
個別の項目のスタイル。 |
||
ページ選択コントロールのスタイル。 |
||
現在選択されている項目のスタイル。 |
各スタイル クラスでサポートされているプロパティについては、「スタイル プロパティ」を参照してください。
DataGrid コントロールには、その内容をページ セグメントに表示するための組み込み機能があります。ページ上の項目数は、PageSize プロパティによって決定されます。PageSize プロパティの値が指定されていない場合、DataGrid コントロールは一度に 10 個の項目をページに表示します。
既定では、このようなページングは無効です。ページングを有効にするには、AllowPaging プロパティを true に設定し、PageIndexChanged イベントを処理するコードを指定します。PageIndexChanged イベントの一般的なロジックでは、表示するページのインデックスを CurrentPageIndex プロパティに設定し、データ ソースをコントロールにもう一度バインドします。多くの場合、表示するページのインデックスには、イベント ハンドラに渡された DataGridPageChangedEventArgs オブジェクトの NewPageIndex プロパティを使用してアクセスします。
標準のページングで、DataGrid コントロールは、表示するすべての項目がデータ ソースに含まれていることを前提としています。DataGrid コントロールは、CurrentPageIndex プロパティで指定されているページ インデックスと、PageSize プロパティで指定されているページ上の項目数に基づいて、現在のページ上の項目のインデックスを計算します。
DataGrid コントロールの外観は、DataGrid コントロールにより生成された <td> タグおよび <tr> タグに、プログラムを使用して属性を追加することにより、さらにカスタマイズできます。タグに属性を挿入するには、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>