DataGrid クラス
アセンブリ: System.Web (system.web.dll 内)


DataGrid コントロールを使用して、データ ソースのフィールドをテーブルの列として表示します。DataGrid コントロールの各行は、データ ソースのレコードを表します。DataGrid コントロールは選択、編集、削除、ページング、並べ替えをサポートしています。
さまざまな列の型があり、それによってコントロール内の列の機能は異なります。使用できるさまざまな列型の一覧を次の表に示します。
列型 | |
---|---|
BoundColumn | データ ソースのフィールドに連結されている列を表示します。各項目はフィールドにテキストとして表示されます。この型は DataGrid コントロールの既定の列型です。 |
ButtonColumn | 列の各項目に対してコマンド ボタンを表示します。この列を使用して、[Add] ボタンや [Remove] ボタンなどのカスタム ボタン コントロールの列を作成できます。 |
EditCommandColumn | |
HyperLinkColumn | 列の各項目の内容をハイパーリンクとして表示します。列の内容は、データ ソースのフィールドまたは静的テキストに連結できます。 |
TemplateColumn |
既定では AutoGenerateColumns プロパティは true に設定されています。つまり、データ ソース内の各フィールドに対して BoundColumn オブジェクトが作成されます。次に、各フィールドはデータ ソースに表示される順序で DataGrid コントロールの列として表示されます。
また、AutoGenerateColumns プロパティを false に設定し、開始および終了の <Columns> タグで囲む列を一覧表示すると、どの列を DataGrid コントロールに表示するかを手動で制御できます。指定した列が、一覧表の順序で Columns コレクションに追加されます。この機能により、DataGrid コントロールの列をプログラムにより制御できます。
![]() |
---|
このコントロールは、ユーザー入力を表示するために使用できます。ユーザー入力には悪意のあるクライアント スクリプトが含まれている可能性があります。アプリケーションに表示する前に、クライアントから送信された実行スクリプト、SQL ステートメントなどのコードの情報はすべて検査してください。ASP.NET には入力要求の検証機能があり、ユーザー入力の中のスクリプトと HTML をブロックできます。検証サーバー コントロールは、ユーザー入力を査定する目的でも用意されています。詳細については、「検証サーバー コントロール構文」を参照してください。 |
ユーザー補助

DataGrid コントロールを使用して、データ ソースの項目を表示する方法を次のコード例に示します。
<%@ Page Language="VB" AutoEventWireup="True" %> <%@ Import Namespace="System.Data" %> <html> <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> <body> <form 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" %> <html> <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> <body> <form 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" %> <html> <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 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 Session("DG4_ShoppingCart") Is Nothing Then Cart = New DataTable() Cart.Columns.Add(New DataColumn("Item", GetType(String))) Cart.Columns.Add(New DataColumn("Price", GetType(String))) Session("DG4_ShoppingCart") = Cart Else Cart = CType(Session("DG4_ShoppingCart"), DataTable) End If CartView = New DataView(Cart) ShoppingCart.DataSource = CartView ShoppingCart.DataBind() If Not IsPostBack Then ' Load this data only once. ItemsGrid.DataSource = CreateDataSource() ItemsGrid.DataBind() End If End Sub 'Page_Load Sub Grid_CartCommand(sender As Object, e As DataGridCommandEventArgs) Dim dr As DataRow = Cart.NewRow() ' e.Item is the table row where the command is raised. ' For bound columns, the value is stored in the Text property of the TableCell. Dim itemCell As TableCell = e.Item.Cells(2) Dim priceCell As TableCell = e.Item.Cells(3) Dim item As String = itemCell.Text Dim price As String = priceCell.Text If CType(e.CommandSource, Button).CommandName = "AddToCart" Then dr(0) = item dr(1) = price Cart.Rows.Add(dr) Else 'Remove from Cart. CartView.RowFilter = "Item" + ChrW(61) + "'" + item + "'" If CartView.Count > 0 Then CartView.Delete(0) End If CartView.RowFilter = "" End If ShoppingCart.DataBind() End Sub 'Grid_CartCommand </script> <body> <form runat=server> <h3>DataGrid Example</h3> <table cellpadding="5"> <tr valign="top"> <td> <b>Product List</b> <asp:DataGrid id="ItemsGrid" BorderColor="black" BorderWidth="1" CellPadding="3" AutoGenerateColumns="false" OnItemCommand="Grid_CartCommand" runat="server"> <HeaderStyle BackColor="#00aaaa"> </HeaderStyle> <Columns> <asp:ButtonColumn HeaderText="Add to cart" ButtonType="PushButton" Text="Add" CommandName="AddToCart" /> <asp:ButtonColumn HeaderText="Remove from cart" ButtonType="PushButton" Text="Remove" CommandName="RemoveFromCart" /> <asp:BoundColumn HeaderText="Item" DataField="StringValue"/> <asp:BoundColumn HeaderText="Price" DataField="CurrencyValue" DataFormatString="{0:c}"> <ItemStyle HorizontalAlign="right"> </ItemStyle> </asp:BoundColumn> </Columns> </asp:DataGrid> </td> <td> <b>Shopping Cart</b> <asp:DataGrid id="ShoppingCart" runat="server" BorderColor="black" BorderWidth="1" GridLines="Both" ShowFooter="false" CellPadding="3" CellSpacing="0"> <HeaderStyle BackColor="#00aaaa"> </HeaderStyle> </asp:DataGrid> </td> </tr> </table> </form> </body> </html>
<%@ Page Language="C#" AutoEventWireup="True" %> <%@ Import Namespace="System.Data" %> <html> <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 < 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 (Session["DG4_ShoppingCart"] == null) { Cart = new DataTable(); Cart.Columns.Add(new DataColumn("Item", typeof(string))); Cart.Columns.Add(new DataColumn("Price", typeof(string))); Session["DG4_ShoppingCart"] = Cart; } else { Cart = (DataTable)Session["DG4_ShoppingCart"]; } CartView = new DataView(Cart); ShoppingCart.DataSource = CartView; ShoppingCart.DataBind(); if (!IsPostBack) { // Load this data only once. ItemsGrid.DataSource= CreateDataSource(); ItemsGrid.DataBind(); } } void Grid_CartCommand(Object sender, DataGridCommandEventArgs e) { DataRow dr = Cart.NewRow(); // e.Item is the table row where the command is raised. // For bound columns, the value is stored in the Text property of the TableCell. TableCell itemCell = e.Item.Cells[2]; TableCell priceCell = e.Item.Cells[3]; string item = itemCell.Text; string price = priceCell.Text; if (((Button)e.CommandSource).CommandName == "AddToCart") { dr[0] = item; dr[1] = price; Cart.Rows.Add(dr); } else { // Remove from Cart. CartView.RowFilter = "Item='" + item + "'"; if (CartView.Count > 0) { CartView.Delete(0); } CartView.RowFilter = ""; } ShoppingCart.DataBind(); } </script> <body> <form runat=server> <h3>DataGrid Example</h3> <table cellpadding="5"> <tr valign="top"> <td> <b>Product List</b> <asp:DataGrid id="ItemsGrid" BorderColor="black" BorderWidth="1" CellPadding="3" AutoGenerateColumns="false" OnItemCommand="Grid_CartCommand" runat="server"> <HeaderStyle BackColor="#00aaaa"> </HeaderStyle> <Columns> <asp:ButtonColumn HeaderText="Add to cart" ButtonType="PushButton" Text="Add" CommandName="AddToCart" /> <asp:ButtonColumn HeaderText="Remove from cart" ButtonType="PushButton" Text="Remove" CommandName="RemoveFromCart" /> <asp:BoundColumn HeaderText="Item" DataField="StringValue"/> <asp:BoundColumn HeaderText="Price" DataField="CurrencyValue" DataFormatString="{0:c}"> <ItemStyle HorizontalAlign="right"> </ItemStyle> </asp:BoundColumn> </Columns> </asp:DataGrid> </td> <td> <b>Shopping Cart</b> <asp:DataGrid id="ShoppingCart" runat="server" BorderColor="black" BorderWidth="1" GridLines="Both" ShowFooter="false" CellPadding="3" CellSpacing="0"> <HeaderStyle BackColor="#00aaaa"> </HeaderStyle> </asp:DataGrid> </td> </tr> </table> </form> </body> </html>
DataGrid コントロールによって生成された <td> タグと <tr> タグに、動的に属性を追加する方法を次のコード例に示します。
<%@ Page Language="VB" AutoEventWireup="True" %> <%@ Import Namespace="System.Data" %> <html> <script runat="server"> Function CreateDataSource() As ICollection Dim dt As DataTable = New DataTable() Dim dr As DataRow Dim i As Integer Dim dv As DataView dt.Columns.Add(New DataColumn("IntegerValue", GetType(Integer))) dt.Columns.Add(New DataColumn("StringValue", GetType(String))) dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double))) For i = 0 to 4 dr = dt.NewRow() dr(0) = i dr(1) = "Item " + i.ToString() dr(2) = 1.23 * (i+1) dt.Rows.Add(dr) Next i dv = New DataView(dt) CreateDataSource = dv End Function Sub Page_Load(sender As Object, e As EventArgs) If Not IsPostBack ' Load this data only once. ItemsGrid.DataSource = CreateDataSource() ItemsGrid.DataBind() End If End Sub Sub Item_Bound(sender As Object, e As DataGridItemEventArgs) Dim itemType As ListItemType Dim intCell As TableCell itemType = CType(e.Item.ItemType, ListItemType) If (itemType <> ListItemType.Header) And _ (itemType <> ListItemType.Footer) And _ (itemType <> ListItemType.Separator) Then ' Get the IntegerValue cell from the grid's column collection. intCell = CType(e.Item.Controls(0), TableCell) ' Add attributes to the cell. intCell.Attributes.Add("id", "intCell" + e.Item.ItemIndex.ToString()) intCell.Attributes.Add("OnClick", _ "Update_intCell" + _ e.Item.ItemIndex.ToString() + _ "()") ' Add attributes to the row. e.Item.Attributes.Add("id", "row" + e.Item.ItemIndex.ToString()) e.Item.Attributes.Add("OnDblClick", _ "Update_row" + _ e.Item.ItemIndex.ToString() + _ "()") End If End Sub </script> <script language="vbscript"> sub Update_intCell0 Alert "You Selected Cell 0." end sub sub Update_intCell1 Alert "You Selected Cell 1." end sub sub Update_intCell2 Alert "You Selected Cell 2." end sub sub Update_intCell3 Alert "You Selected Cell 3." end sub sub Update_intCell4 Alert "You Selected Cell 4." end sub sub UpDate_row0 Alert "You selected the row 0." end sub sub UpDate_row1 Alert "You selected the row 1." end sub sub UpDate_row2 Alert "You selected the row 2." end sub sub UpDate_row3 Alert "You selected the row 3." end sub sub UpDate_row4 Alert "You selected the row 4." end sub </script> <body> <form runat=server> <h3> Adding Attributes to the <td> and <tr> <br> Tags of a DataGrid Control </h3> <asp:DataGrid id="ItemsGrid" runat="server" BorderColor="black" BorderWidth="1" CellPadding="3" ShowFooter="true" OnItemDataBound="Item_Bound" AutoGenerateColumns="false"> <HeaderStyle BackColor="#00aaaa"> </HeaderStyle> <FooterStyle BackColor="#00aaaa"> </FooterStyle> <Columns> <asp:BoundColumn HeaderText="Number" DataField="IntegerValue"> <ItemStyle BackColor="yellow"> </ItemStyle> </asp:BoundColumn> <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><br> Click on one of the cells in the <b>Number</b> column to select the cell. <br><br> Double click on a row to select a row. </form> </body> </html>
<%@ Page Language="C#" AutoEventWireup="True" %> <%@ Import Namespace="System.Data" %> <html> <script 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 < 5; 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(); } } void Item_Bound(Object sender, DataGridItemEventArgs e) { ListItemType itemType = (ListItemType)e.Item.ItemType; if ((itemType != ListItemType.Header) && (itemType != ListItemType.Footer) && (itemType != ListItemType.Separator)) { // Get the IntegerValue cell from the grid's column collection. TableCell intCell = (TableCell)e.Item.Controls[0]; // Add attributes to the cell. intCell.Attributes.Add("id", "intCell" + e.Item.ItemIndex.ToString()); intCell.Attributes.Add("OnClick", "Update_intCell" + e.Item.ItemIndex.ToString() + "()"); // Add attributes to the row. e.Item.Attributes.Add("id", "row" + e.Item.ItemIndex.ToString()); e.Item.Attributes.Add("OnDblClick", "Update_row" + e.Item.ItemIndex.ToString() + "()"); } } </script> <script language="vbscript"> sub Update_intCell0 Alert "You Selected Cell 0." end sub sub Update_intCell1 Alert "You Selected Cell 1." end sub sub Update_intCell2 Alert "You Selected Cell 2." end sub sub Update_intCell3 Alert "You Selected Cell 3." end sub sub Update_intCell4 Alert "You Selected Cell 4." end sub sub UpDate_row0 Alert "You selected the row 0." end sub sub UpDate_row1 Alert "You selected the row 1." end sub sub UpDate_row2 Alert "You selected the row 2." end sub sub UpDate_row3 Alert "You selected the row 3." end sub sub UpDate_row4 Alert "You selected the row 4." end sub </script> <body> <form runat=server> <h3> Adding Attributes to the <td> and <tr> <br> Tags of a DataGrid Control </h3> <asp:DataGrid id="ItemsGrid" runat="server" BorderColor="black" BorderWidth="1" CellPadding="3" ShowFooter="true" OnItemDataBound="Item_Bound" AutoGenerateColumns="false"> <HeaderStyle BackColor="#00aaaa"> </HeaderStyle> <FooterStyle BackColor="#00aaaa"> </FooterStyle> <Columns> <asp:BoundColumn HeaderText="Number" DataField="IntegerValue"> <ItemStyle BackColor="yellow"> </ItemStyle> </asp:BoundColumn> <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><br> Click on one of the cells in the <b>Number</b> column to select the cell. <br><br> Double click on a row to select a row. </form> </body> </html>
<%@ Page Language="JScript" AutoEventWireup="True" %> <%@ Import Namespace="System.Data" %> <html> <script runat="server"> function CreateDataSource() : ICollection { var dt : DataTable = new DataTable(); var dr : DataRow; dt.Columns.Add(new DataColumn("IntegerValue", System.Int32)); dt.Columns.Add(new DataColumn("StringValue", System.String)); dt.Columns.Add(new DataColumn("CurrencyValue", System.Double)); for (var i : int = 0; i < 5; 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) { // Load this data only once. ItemsGrid.DataSource = CreateDataSource(); ItemsGrid.DataBind(); } } function Item_Bound(sender, e : DataGridItemEventArgs) { var itemType : ListItemType = ListItemType(e.Item.ItemType); if ((itemType != ListItemType.Header) && (itemType != ListItemType.Footer) && (itemType != ListItemType.Separator)) { // Get the IntegerValue cell from the grid's column collection. var intCell : TableCell = TableCell(e.Item.Controls[0]); // Add attributes to the cell. intCell.Attributes.Add("id", "intCell" + e.Item.ItemIndex.ToString()); intCell.Attributes.Add("OnClick", "Update_intCell" + e.Item.ItemIndex.ToString() + "()"); // Add attributes to the row. e.Item.Attributes.Add("id", "row" + e.Item.ItemIndex.ToString()); e.Item.Attributes.Add("OnDblClick", "Update_row" + e.Item.ItemIndex.ToString() + "()"); } } </script> <script language="vbscript"> sub Update_intCell0 Alert "You Selected Cell 0." end sub sub Update_intCell1 Alert "You Selected Cell 1." end sub sub Update_intCell2 Alert "You Selected Cell 2." end sub sub Update_intCell3 Alert "You Selected Cell 3." end sub sub Update_intCell4 Alert "You Selected Cell 4." end sub sub UpDate_row0 Alert "You selected the row 0." end sub sub UpDate_row1 Alert "You selected the row 1." end sub sub UpDate_row2 Alert "You selected the row 2." end sub sub UpDate_row3 Alert "You selected the row 3." end sub sub UpDate_row4 Alert "You selected the row 4." end sub </script> <body> <form runat=server> <h3> Adding Attributes to the <td> and <tr> <br> Tags of a DataGrid Control </h3> <asp:DataGrid id="ItemsGrid" runat="server" BorderColor="black" BorderWidth="1" CellPadding="3" ShowFooter="true" OnItemDataBound="Item_Bound" AutoGenerateColumns="false"> <HeaderStyle BackColor="#00aaaa"> </HeaderStyle> <FooterStyle BackColor="#00aaaa"> </FooterStyle> <Columns> <asp:BoundColumn HeaderText="Number" DataField="IntegerValue"> <ItemStyle BackColor="yellow"> </ItemStyle> </asp:BoundColumn> <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><br> Click on one of the cells in the <b>Number</b> column to select the cell. <br><br> Double click on a row to select a row. </form> </body> </html>
<%@ Page Language="VB" AutoEventWireup="True" %> <%@ Import Namespace="System.Data" %> <html> <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 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 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 ItemsGrid.DataSource = CreateDataSource() ItemsGrid.DataBind() End If End Sub Sub Button_Click(sender As Object, e As EventArgs) ' Count the number of selected items in the DataGrid control. Dim count As Integer = 0 ' Display the selected items. Message.Text = "You Selected: <br>" ' Iterate through each item (row) in the DataGrid control ' and determine whether it is selected. Dim item As DataGridItem For Each item In ItemsGrid.Items DetermineSelection(item, count) Next ' If no items are selected, display the appropriate message. If count = 0 Then Message.Text = "No items selected" End If End Sub Sub DetermineSelection(item As DataGridItem, ByRef count As Integer) ' Retrieve the SelectCheckBox CheckBox control from the specified ' item (row) in the DataGrid control. Dim selection As CheckBox = CType(item.FindControl("SelectCheckBox"), CheckBox) ' If the item is selected, display the appropriate message and ' increment the count of selected items. If Not selection Is Nothing Then If selection.Checked Then Message.Text &= "- " & item.Cells(1).Text & "<br>" count = count + 1 End If End If End Sub </script> <body> <form runat=server> <h3>DataGrid Example</h3> <b>Product List</b> <asp:DataGrid id="ItemsGrid" BorderColor="black" BorderWidth="1" CellPadding="3" AutoGenerateColumns="False" runat="server"> <HeaderStyle BackColor="#00aaaa"> </HeaderStyle> <Columns> <asp:BoundColumn DataField="IntegerValue" HeaderText="Item"/> <asp:BoundColumn DataField="StringValue" HeaderText="Description"/> <asp:BoundColumn DataField="CurrencyValue" HeaderText="Price" DataFormatString="{0:c}"> <ItemStyle HorizontalAlign="Right"> </ItemStyle> </asp:BoundColumn> <asp:TemplateColumn HeaderText="Select Item"> <ItemTemplate> <asp:CheckBox id="SelectCheckBox" Text="Add to Cart" Checked="False" runat="server"/> </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:DataGrid> <br><br> <asp:Button id="SubmitButton" Text="Submit" OnClick = "Button_Click" runat="server"/> <br><br> <asp:Label id="Message" runat="server"/> </form> </body> </html>
<%@ Page Language="C#" AutoEventWireup="True" %> <%@ Import Namespace="System.Data" %> <html> <script runat="server"> 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 < 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) { // Load sample data only once when the page is first loaded. if (!IsPostBack) { ItemsGrid.DataSource = CreateDataSource(); ItemsGrid.DataBind(); } } void Button_Click(Object sender, EventArgs e) { // Count the number of selected items in the DataGrid control. int count = 0; // Display the selected times. Message.Text = "You Selected: <br>"; // Iterate through each item (row) in the DataGrid control and // determine whether it is selected. foreach (DataGridItem item in ItemsGrid.Items) { DetermineSelection(item, ref count); } // If no items are selected, display the appropriate message. if (count == 0) { Message.Text = "No items selected"; } } void DetermineSelection(DataGridItem item, ref int count) { // Retrieve the SelectCheckBox CheckBox control from the specified // item (row) in the DataGrid control. CheckBox selection = (CheckBox)item.FindControl("SelectCheckBox"); // If the item is selected, display the appropriate message and // increment the count of selected items. if (selection != null) { if (selection.Checked) { Message.Text += "- " + item.Cells[1].Text + "<br>"; count++; } } } </script> <body> <form runat=server> <h3>DataGrid Example</h3> <b>Product List</b> <asp:DataGrid id="ItemsGrid" BorderColor="black" BorderWidth="1" CellPadding="3" AutoGenerateColumns="False" runat="server"> <HeaderStyle BackColor="#00aaaa"> </HeaderStyle> <Columns> <asp:BoundColumn DataField="IntegerValue" HeaderText="Item"/> <asp:BoundColumn DataField="StringValue" HeaderText="Description"/> <asp:BoundColumn DataField="CurrencyValue" HeaderText="Price" DataFormatString="{0:c}"> <ItemStyle HorizontalAlign="Right"> </ItemStyle> </asp:BoundColumn> <asp:TemplateColumn HeaderText="Select Item"> <ItemTemplate> <asp:CheckBox id="SelectCheckBox" Text="Add to Cart" Checked="False" runat="server"/> </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:DataGrid> <br><br> <asp:Button id="SubmitButton" Text="Submit" OnClick = "Button_Click" runat="server"/> <br><br> <asp:Label id="Message" runat="server"/> </form> </body> </html>

System.Web.UI.Control
System.Web.UI.WebControls.WebControl
System.Web.UI.WebControls.BaseDataList
System.Web.UI.WebControls.DataGrid


Windows 98, Windows 2000 SP4, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


DataGrid クラス
アセンブリ: System.Windows.Forms (system.windows.forms.dll 内)

<ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)> _ <ComVisibleAttribute(True)> _ Public Class DataGrid Inherits Control Implements ISupportInitialize, IDataGridEditingService
[ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)] [ComVisibleAttribute(true)] public class DataGrid : Control, ISupportInitialize, IDataGridEditingService
[ClassInterfaceAttribute(ClassInterfaceType::AutoDispatch)] [ComVisibleAttribute(true)] public ref class DataGrid : public Control, ISupportInitialize, IDataGridEditingService

System.Windows.Forms.DataGrid は、子テーブルへの Web に似たリンクを表示します。リンクをクリックすると子テーブルへ移動できます。子テーブルが表示されると、[戻る] ボタンがキャプションに表示され、クリックすると親テーブルへ戻ることができます。親行からのデータは、キャプションの下と列ヘッダーの上に表示されます。[戻る] ボタンの右側にあるボタンをクリックすると、親行の情報を非表示にできます。
実行時に、System.Windows.Forms.DataGrid のテーブルを表示するには、SetDataBinding メソッドを使用して DataSource プロパティと DataMember プロパティを有効なデータ ソースに設定します。有効なデータ ソースを次に示します。
-
DataTable
-
DataView
-
DataViewManager
DataSet クラスの詳細については、ADO.NET での DataSet の使用 のトピックを参照してください。
作成したグリッドで、ユーザーはデータを編集できるが、新しい行を追加できないようにするには、DataView をデータ ソースとして使用し、AllowNew プロパティを false に設定します。
データ ソースは BindingManagerBase オブジェクトによってさらに管理されます。データ ソースの各テーブルに対して、フォームの BindingContext から BindingManagerBase を返すことができます。たとえば、関連付けられた BindingManagerBase オブジェクトの Count プロパティを返すと、データ ソースによって格納された行の数を確認できます。
データを検証するには、データとそのイベントを表している、基になるオブジェクトを使用します。たとえば、データが DataSet の DataTable から発生している場合は、ColumnChanging イベントと RowChanging イベントを使用します。
![]() |
---|
列の数は GridColumnStylesCollection のメンバを追加または削除することでカスタマイズでき、行は列で並べ替えできるため、RowNumber プロパティ値と ColumnNumber プロパティ値は、必ずしも DataTable 内の DataRow インデックスと DataColumn インデックスに対応しているとは限りません。このため、データを検証するには、これらのプロパティを Validating イベントで使用しないでください。 |
選択されているセルを確認するには、CurrentCell プロパティを使用します。セルの行インデックスおよび列インデックス、または単一の DataGridCell を設定できる Item プロパティを使用して、任意のセルの値を変更します。ユーザーがいつ別のセルを選択するかを検出するには、CurrentCellChanged イベントを監視します。
ユーザーがコントロールのどの部分をクリックしたかを確認するには、MouseDown イベントの HitTest メソッドを使用します。HitTest メソッドによって、クリックされた領域の列と行を格納している DataGrid.HitTestInfo オブジェクトが返されます。
実行時にコントロールの外観を管理するには、色とキャプションの属性を設定するために、CaptionForeColor、CaptionBackColor、CaptionFont などのプロパティを使用できます。
さらに、表示された 1 つ以上のグリッドの外観を変更するには、DataGridTableStyle オブジェクトを作成して、そのオブジェクトを TableStyles プロパティを通じてアクセスする GridTableStylesCollection に追加します。たとえば、DataSource が 3 つの DataTable オブジェクトを格納している DataSet に設定されている場合は、3 つの DataGridTableStyle オブジェクトをコレクションの各テーブルに 1 つ追加できます。DataTable を使用して各 DataGridTableStyle オブジェクトを同期するには、DataGridTableStyle の MappingName を DataTable の TableName に設定します。オブジェクトの配列へのバインドの詳細については、DataGridTableStyle.MappingName プロパティのトピックを参照してください。
テーブルのカスタマイズされたビューを作成するには、DataGridTextBoxColumn クラスまたは DataGridBoolColumn クラスのインスタンスを作成し、TableStyles プロパティを使用してアクセスされる GridTableStylesCollection にオブジェクトを追加します。このクラスは両方とも、DataGridColumnStyle から継承します。各列スタイルに対して、MappingName を、グリッドに表示する列の ColumnName に設定します。列を非表示にするには、MappingName を有効な ColumnName 以外の値に設定します。
列のテキストの書式を指定するには、DataGridTextBoxColumn の Format プロパティを、日付と時刻の書式指定文字列 または 標準の数値書式指定文字列 の値のいずれかに設定します。
DataGrid をオブジェクトの厳密に型指定された配列にバインドするには、オブジェクト型にパブリック プロパティが含まれている必要があります。配列を表示する DataGridTableStyle を作成するには、DataGridTableStyle.MappingName プロパティを typename[] に設定します。なお、この typename は実際のオブジェクト型名に置き換えてください。また、MappingName プロパティでは大文字と小文字が区別されることに注意してください。型の名前は正確に指定する必要があります。例については、MappingName プロパティのトピックを参照してください。
また、DataGrid を ArrayList にバインドできます。ArrayList の特長は、複数の型のオブジェクトを格納できることです。ただし、DataGrid はリスト内のすべての項目の型が 1 番目の項目の型と同じ場合に限り、リストにバインドできます。つまり、すべてのオブジェクトの型が同じであるか、リスト内の最初の項目と同じクラスからすべてのクラスが継承している必要があります。たとえば、リスト内の最初の項目が Control の場合、2 番目の項目は (Control から継承した) TextBox にできます。逆に、1 番目の項目が TextBox の場合、2 番目のオブジェクトが Control になることはできません。さらに、ArrayList は、バインディングするときは、項目を含んでいる必要があります。空の ArrayList の場合、空のグリッドとなります。さらに、ArrayList のオブジェクトにはパブリック プロパティが含まれている必要があります。ArrayList にバインディングするときは、DataGridTableStyle の MappingName を "ArrayList" (型の名前) に設定します。
各 DataGridTableStyle では、System.Windows.Forms.DataGrid コントロールの設定をオーバーライドする、色とキャプションの属性を設定できます。ただし、これらのプロパティが設定されていない場合は、コントロールの設定には既定の設定が使用されます。DataGridTableStyle プロパティでオーバーライドできるプロパティを次に示します。
-
AllowSorting
-
AlternatingBackColor
-
ColumnHeadersVisible
-
ForeColor
-
GridLineColor
-
GridLineStyle
-
HeaderBackColor
-
HeaderFont
-
HeaderForeColor
-
LinkColor
-
PreferredColumnWidth
-
PreferredRowHeight
-
RowHeadersVisible
-
RowHeaderWidth
-
SelectionBackColor
-
SelectionForeColor
各列の外観をカスタマイズするには、DataGridColumnStyle オブジェクトを各 DataGridTableStyle の GridColumnStyles プロパティを通じてアクセスする GridColumnStylesCollection に追加します。DataTable の DataColumn を使用して各 DataGridColumnStyle を同期するには、MappingName を DataColumn の ColumnName に設定します。DataGridColumnStyle を構築するときは、列データの表示方法を指定する書式指定文字列を設定することもできます。たとえば、テーブルに格納されている日付を列で表示するときに、短い日付書式を使用するように指定できます。
![]() |
---|
DataGridView コントロールは DataGrid コントロールの後継であり、新しい機能を追加しますが、必要に応じて下位互換性および将来の使用のために DataGrid コントロールを保持することもできます。詳細については、「Windows フォームの DataGridView コントロールと DataGrid コントロールの違いについて」を参照してください。 |

Windows フォーム、2 つの DataTable オブジェクトを格納する DataSet、および 2 つのテーブルを関連付ける DataRelation を作成するコード例を次に示します。さらに、データを表示するために SetDataBinding メソッドを通じて、System.Windows.Forms.DataGrid コントロールが DataSet にバインドされます。フォームのボタンを変更してグリッドの外観を変更するには、2 つの DataGridTableStyle オブジェクトを作成し、各オブジェクトの MappingName を DataTable オブジェクトのいずれかの TableName に設定します。この例では、HitTest メソッドを使用して、列、行、およびクリックされているグリッドの部分を出力する MouseUp イベントのコードも示します。
Option Explicit Option Strict Imports System Imports System.ComponentModel Imports System.Data Imports System.Drawing Imports System.Windows.Forms Public Class Form1 Inherits System.Windows.Forms.Form Private components As System.ComponentModel.Container Private button1 As Button Private button2 As Button Private myDataGrid As DataGrid Private myDataSet As DataSet Private TablesAlreadyAdded As Boolean Public Sub New() ' Required for Windows Form Designer support. InitializeComponent() ' Call SetUp to bind the controls. SetUp() End Sub Private Sub InitializeComponent() ' Create the form and its controls. Me.components = New System.ComponentModel.Container() Me.button1 = New System.Windows.Forms.Button() Me.button2 = New System.Windows.Forms.Button() Me.myDataGrid = New DataGrid() Me.Text = "DataGrid Control Sample" Me.ClientSize = New System.Drawing.Size(450, 330) button1.Location = New Point(24, 16) button1.Size = New System.Drawing.Size(120, 24) button1.Text = "Change Appearance" AddHandler button1.Click, AddressOf button1_Click button2.Location = New Point(150, 16) button2.Size = New System.Drawing.Size(120, 24) button2.Text = "Get Binding Manager" AddHandler button2.Click, AddressOf button2_Click myDataGrid.Location = New Point(24, 50) myDataGrid.Size = New Size(300, 200) myDataGrid.CaptionText = "Microsoft DataGrid Control" AddHandler myDataGrid.MouseUp, AddressOf Grid_MouseUp Me.Controls.Add(button1) Me.Controls.Add(button2) Me.Controls.Add(myDataGrid) End Sub Public Shared Sub Main() Application.Run(New Form1()) End Sub Private Sub SetUp() ' Create a DataSet with two tables and one relation. MakeDataSet() ' Bind the DataGrid to the DataSet. The dataMember ' specifies that the Customers table should be displayed. myDataGrid.SetDataBinding(myDataSet, "Customers") End Sub Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) If TablesAlreadyAdded = True Then Exit Sub AddCustomDataTableStyle() End Sub Private Sub AddCustomDataTableStyle() Dim ts1 As New DataGridTableStyle() ts1.MappingName = "Customers" ' Set other properties. ts1.AlternatingBackColor = Color.LightGray ' Add a GridColumnStyle and set its MappingName ' to the name of a DataColumn in the DataTable. ' Set the HeaderText and Width properties. Dim boolCol As New DataGridBoolColumn() boolCol.MappingName = "Current" boolCol.HeaderText = "IsCurrent Customer" boolCol.Width = 150 ts1.GridColumnStyles.Add(boolCol) ' Add a second column style. Dim TextCol As New DataGridTextBoxColumn() TextCol.MappingName = "custName" TextCol.HeaderText = "Customer Name" TextCol.Width = 250 ts1.GridColumnStyles.Add(TextCol) ' Create the second table style with columns. Dim ts2 As New DataGridTableStyle() ts2.MappingName = "Orders" ' Set other properties. ts2.AlternatingBackColor = Color.LightBlue ' Create new ColumnStyle objects Dim cOrderDate As New DataGridTextBoxColumn() cOrderDate.MappingName = "OrderDate" cOrderDate.HeaderText = "Order Date" cOrderDate.Width = 100 ts2.GridColumnStyles.Add(cOrderDate) ' Use a PropertyDescriptor to create a formatted ' column. First get the PropertyDescriptorCollection ' for the data source and data member. Dim pcol As PropertyDescriptorCollection = _ Me.BindingContext(myDataSet, "Customers.custToOrders"). _ GetItemProperties() ' Create a formatted column using a PropertyDescriptor. ' The formatting character "c" specifies a currency format. */ Dim csOrderAmount As _ New DataGridTextBoxColumn(pcol("OrderAmount"), "c", True) csOrderAmount.MappingName = "OrderAmount" csOrderAmount.HeaderText = "Total" csOrderAmount.Width = 100 ts2.GridColumnStyles.Add(csOrderAmount) ' Add the DataGridTableStyle instances to ' the GridTableStylesCollection. myDataGrid.TableStyles.Add(ts1) myDataGrid.TableStyles.Add(ts2) ' Sets the TablesAlreadyAdded to true so this doesn't happen again. TablesAlreadyAdded = true End Sub Private Sub button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Dim bmGrid As BindingManagerBase bmGrid = BindingContext(myDataSet, "Customers") MessageBox.Show(("Current BindingManager Position: " & bmGrid.Position)) End Sub Private Sub Grid_MouseUp(sender As Object, e As MouseEventArgs) ' Create a HitTestInfo object using the HitTest method. ' Get the DataGrid by casting sender. Dim myGrid As DataGrid = CType(sender, DataGrid) Dim myHitInfo As DataGrid.HitTestInfo = myGrid.HitTest(e.X, e.Y) Console.WriteLine(myHitInfo) Console.WriteLine(myHitInfo.Type) Console.WriteLine(myHitInfo.Row) Console.WriteLine(myHitInfo.Column) End Sub ' Create a DataSet with two tables and populate it. Private Sub MakeDataSet() ' Create a DataSet. myDataSet = New DataSet("myDataSet") ' Create two DataTables. Dim tCust As New DataTable("Customers") Dim tOrders As New DataTable("Orders") ' Create two columns, and add them to the first table. Dim cCustID As New DataColumn("CustID", GetType(Integer)) Dim cCustName As New DataColumn("CustName") Dim cCurrent As New DataColumn("Current", GetType(Boolean)) tCust.Columns.Add(cCustID) tCust.Columns.Add(cCustName) tCust.Columns.Add(cCurrent) ' Create three columns, and add them to the second table. Dim cID As New DataColumn("CustID", GetType(Integer)) Dim cOrderDate As New DataColumn("orderDate", GetType(DateTime)) Dim cOrderAmount As New DataColumn("OrderAmount", GetType(Decimal)) tOrders.Columns.Add(cOrderAmount) tOrders.Columns.Add(cID) tOrders.Columns.Add(cOrderDate) ' Add the tables to the DataSet. myDataSet.Tables.Add(tCust) myDataSet.Tables.Add(tOrders) ' Create a DataRelation, and add it to the DataSet. Dim dr As New DataRelation("custToOrders", cCustID, cID) myDataSet.Relations.Add(dr) ' Populates the tables. For each customer and order, ' creates two DataRow variables. Dim newRow1 As DataRow Dim newRow2 As DataRow ' Create three customers in the Customers Table. Dim i As Integer For i = 1 To 3 newRow1 = tCust.NewRow() newRow1("custID") = i ' Add the row to the Customers table. tCust.Rows.Add(newRow1) Next i ' Give each customer a distinct name. tCust.Rows(0)("custName") = "Customer1" tCust.Rows(1)("custName") = "Customer2" tCust.Rows(2)("custName") = "Customer3" ' Give the Current column a value. tCust.Rows(0)("Current") = True tCust.Rows(1)("Current") = True tCust.Rows(2)("Current") = False ' For each customer, create five rows in the Orders table. For i = 1 To 3 Dim j As Integer For j = 1 To 5 newRow2 = tOrders.NewRow() newRow2("CustID") = i newRow2("orderDate") = New DateTime(2001, i, j * 2) newRow2("OrderAmount") = i * 10 + j * 0.1 ' Add the row to the Orders table. tOrders.Rows.Add(newRow2) Next j Next i End Sub End Class
using System; using System.ComponentModel; using System.Data; using System.Drawing; using System.Windows.Forms; public class Form1 : System.Windows.Forms.Form { private System.ComponentModel.Container components; private Button button1; private Button button2; private DataGrid myDataGrid; private DataSet myDataSet; private bool TablesAlreadyAdded; public Form1() { // Required for Windows Form Designer support. InitializeComponent(); // Call SetUp to bind the controls. SetUp(); } protected override void Dispose( bool disposing ){ if( disposing ){ if (components != null){ components.Dispose();} } base.Dispose( disposing ); } private void InitializeComponent() { // Create the form and its controls. this.components = new System.ComponentModel.Container(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.myDataGrid = new DataGrid(); this.Text = "DataGrid Control Sample"; this.ClientSize = new System.Drawing.Size(450, 330); button1.Location = new Point(24, 16); button1.Size = new System.Drawing.Size(120, 24); button1.Text = "Change Appearance"; button1.Click+=new System.EventHandler(button1_Click); button2.Location = new Point(150, 16); button2.Size = new System.Drawing.Size(120, 24); button2.Text = "Get Binding Manager"; button2.Click+=new System.EventHandler(button2_Click); myDataGrid.Location = new Point(24, 50); myDataGrid.Size = new Size(300, 200); myDataGrid.CaptionText = "Microsoft DataGrid Control"; myDataGrid.MouseUp += new MouseEventHandler(Grid_MouseUp); this.Controls.Add(button1); this.Controls.Add(button2); this.Controls.Add(myDataGrid); } public static void Main() { Application.Run(new Form1()); } private void SetUp() { // Create a DataSet with two tables and one relation. MakeDataSet(); /* Bind the DataGrid to the DataSet. The dataMember specifies that the Customers table should be displayed.*/ myDataGrid.SetDataBinding(myDataSet, "Customers"); } private void button1_Click(object sender, System.EventArgs e) { if(TablesAlreadyAdded) return; AddCustomDataTableStyle(); } private void AddCustomDataTableStyle() { DataGridTableStyle ts1 = new DataGridTableStyle(); ts1.MappingName = "Customers"; // Set other properties. ts1.AlternatingBackColor = Color.LightGray; /* Add a GridColumnStyle and set its MappingName to the name of a DataColumn in the DataTable. Set the HeaderText and Width properties. */ DataGridColumnStyle boolCol = new DataGridBoolColumn(); boolCol.MappingName = "Current"; boolCol.HeaderText = "IsCurrent Customer"; boolCol.Width = 150; ts1.GridColumnStyles.Add(boolCol); // Add a second column style. DataGridColumnStyle TextCol = new DataGridTextBoxColumn(); TextCol.MappingName = "custName"; TextCol.HeaderText = "Customer Name"; TextCol.Width = 250; ts1.GridColumnStyles.Add(TextCol); // Create the second table style with columns. DataGridTableStyle ts2 = new DataGridTableStyle(); ts2.MappingName = "Orders"; // Set other properties. ts2.AlternatingBackColor = Color.LightBlue; // Create new ColumnStyle objects DataGridColumnStyle cOrderDate = new DataGridTextBoxColumn(); cOrderDate.MappingName = "OrderDate"; cOrderDate.HeaderText = "Order Date"; cOrderDate.Width = 100; ts2.GridColumnStyles.Add(cOrderDate); /* Use a PropertyDescriptor to create a formatted column. First get the PropertyDescriptorCollection for the data source and data member. */ PropertyDescriptorCollection pcol = this.BindingContext [myDataSet, "Customers.custToOrders"].GetItemProperties(); /* Create a formatted column using a PropertyDescriptor. The formatting character "c" specifies a currency format. */ DataGridColumnStyle csOrderAmount = new DataGridTextBoxColumn(pcol["OrderAmount"], "c", true); csOrderAmount.MappingName = "OrderAmount"; csOrderAmount.HeaderText = "Total"; csOrderAmount.Width = 100; ts2.GridColumnStyles.Add(csOrderAmount); /* Add the DataGridTableStyle instances to the GridTableStylesCollection. */ myDataGrid.TableStyles.Add(ts1); myDataGrid.TableStyles.Add(ts2); // Sets the TablesAlreadyAdded to true so this doesn't happen again. TablesAlreadyAdded=true; } private void button2_Click(object sender, System.EventArgs e) { BindingManagerBase bmGrid; bmGrid = BindingContext[myDataSet, "Customers"]; MessageBox.Show("Current BindingManager Position: " + bmGrid.Position); } private void Grid_MouseUp(object sender, MouseEventArgs e) { // Create a HitTestInfo object using the HitTest method. // Get the DataGrid by casting sender. DataGrid myGrid = (DataGrid)sender; DataGrid.HitTestInfo myHitInfo = myGrid.HitTest(e.X, e.Y); Console.WriteLine(myHitInfo); Console.WriteLine(myHitInfo.Type); Console.WriteLine(myHitInfo.Row); Console.WriteLine(myHitInfo.Column); } // Create a DataSet with two tables and populate it. private void MakeDataSet() { // Create a DataSet. myDataSet = new DataSet("myDataSet"); // Create two DataTables. DataTable tCust = new DataTable("Customers"); DataTable tOrders = new DataTable("Orders"); // Create two columns, and add them to the first table. DataColumn cCustID = new DataColumn("CustID", typeof(int)); DataColumn cCustName = new DataColumn("CustName"); DataColumn cCurrent = new DataColumn("Current", typeof(bool)); tCust.Columns.Add(cCustID); tCust.Columns.Add(cCustName); tCust.Columns.Add(cCurrent); // Create three columns, and add them to the second table. DataColumn cID = new DataColumn("CustID", typeof(int)); DataColumn cOrderDate = new DataColumn("orderDate",typeof(DateTime)); DataColumn cOrderAmount = new DataColumn("OrderAmount", typeof(decimal)); tOrders.Columns.Add(cOrderAmount); tOrders.Columns.Add(cID); tOrders.Columns.Add(cOrderDate); // Add the tables to the DataSet. myDataSet.Tables.Add(tCust); myDataSet.Tables.Add(tOrders); // Create a DataRelation, and add it to the DataSet. DataRelation dr = new DataRelation ("custToOrders", cCustID , cID); myDataSet.Relations.Add(dr); /* Populates the tables. For each customer and order, creates two DataRow variables. */ DataRow newRow1; DataRow newRow2; // Create three customers in the Customers Table. for(int i = 1; i < 4; i++) { newRow1 = tCust.NewRow(); newRow1["custID"] = i; // Add the row to the Customers table. tCust.Rows.Add(newRow1); } // Give each customer a distinct name. tCust.Rows[0]["custName"] = "Customer1"; tCust.Rows[1]["custName"] = "Customer2"; tCust.Rows[2]["custName"] = "Customer3"; // Give the Current column a value. tCust.Rows[0]["Current"] = true; tCust.Rows[1]["Current"] = true; tCust.Rows[2]["Current"] = false; // For each customer, create five rows in the Orders table. for(int i = 1; i < 4; i++) { for(int j = 1; j < 6; j++) { newRow2 = tOrders.NewRow(); newRow2["CustID"]= i; newRow2["orderDate"]= new DateTime(2001, i, j * 2); newRow2["OrderAmount"] = i * 10 + j * .1; // Add the row to the Orders table. tOrders.Rows.Add(newRow2); } } } }
#using <system.dll> #using <system.data.dll> #using <system.drawing.dll> #using <system.windows.forms.dll> #using <system.xml.dll> using namespace System; using namespace System::ComponentModel; using namespace System::Data; using namespace System::Drawing; using namespace System::Windows::Forms; #define null 0 public ref class Form1: public System::Windows::Forms::Form { private: System::ComponentModel::Container^ components; Button^ button1; Button^ button2; DataGrid^ myDataGrid; DataSet^ myDataSet; bool TablesAlreadyAdded; public: Form1() { // Required for Windows Form Designer support. InitializeComponent(); // Call SetUp to bind the controls. SetUp(); } public: ~Form1() { if ( components != nullptr ) { delete components; } } private: void InitializeComponent() { // Create the form and its controls. this->components = gcnew System::ComponentModel::Container; this->button1 = gcnew System::Windows::Forms::Button; this->button2 = gcnew System::Windows::Forms::Button; this->myDataGrid = gcnew DataGrid; this->Text = "DataGrid Control Sample"; this->ClientSize = System::Drawing::Size( 450, 330 ); button1->Location = System::Drawing::Point( 24, 16 ); button1->Size = System::Drawing::Size( 120, 24 ); button1->Text = "Change Appearance"; button1->Click += gcnew System::EventHandler( this, &Form1::button1_Click ); button2->Location = System::Drawing::Point( 150, 16 ); button2->Size = System::Drawing::Size( 120, 24 ); button2->Text = "Get Binding Manager"; button2->Click += gcnew System::EventHandler( this, &Form1::button2_Click ); myDataGrid->Location = System::Drawing::Point( 24, 50 ); myDataGrid->Size = System::Drawing::Size( 300, 200 ); myDataGrid->CaptionText = "Microsoft DataGrid Control"; myDataGrid->MouseUp += gcnew MouseEventHandler( this, &Form1::Grid_MouseUp ); this->Controls->Add( button1 ); this->Controls->Add( button2 ); this->Controls->Add( myDataGrid ); } void SetUp() { // Create a DataSet with two tables and one relation. MakeDataSet(); /* Bind the DataGrid to the DataSet. The dataMember specifies that the Customers table should be displayed.*/ myDataGrid->SetDataBinding( myDataSet, "Customers" ); } private: void button1_Click( Object^ sender, System::EventArgs^ e ) { if ( TablesAlreadyAdded ) return; AddCustomDataTableStyle(); } private: void AddCustomDataTableStyle() { DataGridTableStyle^ ts1 = gcnew DataGridTableStyle; ts1->MappingName = "Customers"; // Set other properties. ts1->AlternatingBackColor = Color::LightGray; /* Add a GridColumnStyle and set its MappingName to the name of a DataColumn in the DataTable. Set the HeaderText and Width properties. */ DataGridColumnStyle^ boolCol = gcnew DataGridBoolColumn; boolCol->MappingName = "Current"; boolCol->HeaderText = "IsCurrent Customer"; boolCol->Width = 150; ts1->GridColumnStyles->Add( boolCol ); // Add a second column style. DataGridColumnStyle^ TextCol = gcnew DataGridTextBoxColumn; TextCol->MappingName = "custName"; TextCol->HeaderText = "Customer Name"; TextCol->Width = 250; ts1->GridColumnStyles->Add( TextCol ); // Create the second table style with columns. DataGridTableStyle^ ts2 = gcnew DataGridTableStyle; ts2->MappingName = "Orders"; // Set other properties. ts2->AlternatingBackColor = Color::LightBlue; // Create new ColumnStyle objects DataGridColumnStyle^ cOrderDate = gcnew DataGridTextBoxColumn; cOrderDate->MappingName = "OrderDate"; cOrderDate->HeaderText = "Order Date"; cOrderDate->Width = 100; ts2->GridColumnStyles->Add( cOrderDate ); /* Use a PropertyDescriptor to create a formatted column. First get the PropertyDescriptorCollection for the data source and data member. */ PropertyDescriptorCollection^ pcol = this->BindingContext[myDataSet, "Customers.custToOrders"]->GetItemProperties(); /* Create a formatted column using a PropertyDescriptor. The formatting character "c" specifies a currency format. */ DataGridColumnStyle^ csOrderAmount = gcnew DataGridTextBoxColumn( pcol[ "OrderAmount" ],"c",true ); csOrderAmount->MappingName = "OrderAmount"; csOrderAmount->HeaderText = "Total"; csOrderAmount->Width = 100; ts2->GridColumnStyles->Add( csOrderAmount ); /* Add the DataGridTableStyle instances to the GridTableStylesCollection. */ myDataGrid->TableStyles->Add( ts1 ); myDataGrid->TableStyles->Add( ts2 ); // Sets the TablesAlreadyAdded to true so this doesn't happen again. TablesAlreadyAdded = true; } private: void button2_Click( Object^ sender, System::EventArgs^ e ) { BindingManagerBase^ bmGrid; bmGrid = BindingContext[myDataSet, "Customers"]; MessageBox::Show( String::Concat( "Current BindingManager Position: ", bmGrid->Position )->ToString() ); } private: void Grid_MouseUp( Object^ sender, MouseEventArgs^ e ) { // Create a HitTestInfo object using the HitTest method. // Get the DataGrid by casting sender. DataGrid^ myGrid = dynamic_cast<DataGrid^>(sender); DataGrid::HitTestInfo ^ myHitInfo = myGrid->HitTest( e->X, e->Y ); Console::WriteLine( myHitInfo ); Console::WriteLine( myHitInfo->Type ); Console::WriteLine( myHitInfo->Row ); Console::WriteLine( myHitInfo->Column ); } // Create a DataSet with two tables and populate it. void MakeDataSet() { // Create a DataSet. myDataSet = gcnew DataSet( "myDataSet" ); // Create two DataTables. DataTable^ tCust = gcnew DataTable( "Customers" ); DataTable^ tOrders = gcnew DataTable( "Orders" ); // Create two columns, and add them to the first table. DataColumn^ cCustID = gcnew DataColumn( "CustID",__int32::typeid ); DataColumn^ cCustName = gcnew DataColumn( "CustName" ); DataColumn^ cCurrent = gcnew DataColumn( "Current",bool::typeid ); tCust->Columns->Add( cCustID ); tCust->Columns->Add( cCustName ); tCust->Columns->Add( cCurrent ); // Create three columns, and add them to the second table. DataColumn^ cID = gcnew DataColumn( "CustID",__int32::typeid ); DataColumn^ cOrderDate = gcnew DataColumn( "orderDate",DateTime::typeid ); DataColumn^ cOrderAmount = gcnew DataColumn( "OrderAmount",Decimal::typeid ); tOrders->Columns->Add( cOrderAmount ); tOrders->Columns->Add( cID ); tOrders->Columns->Add( cOrderDate ); // Add the tables to the DataSet. myDataSet->Tables->Add( tCust ); myDataSet->Tables->Add( tOrders ); // Create a DataRelation, and add it to the DataSet. DataRelation^ dr = gcnew DataRelation( "custToOrders",cCustID,cID ); myDataSet->Relations->Add( dr ); /* Populate the tables. For each customer and order, create need two DataRow variables. */ DataRow^ newRow1; DataRow^ newRow2; // Create three customers in the Customers Table. for ( int i = 1; i < 4; i++ ) { newRow1 = tCust->NewRow(); newRow1[ "custID" ] = i; // Add the row to the Customers table. tCust->Rows->Add( newRow1 ); } tCust->Rows[ 0 ][ "custName" ] = "Customer1"; tCust->Rows[ 1 ][ "custName" ] = "Customer2"; tCust->Rows[ 2 ][ "custName" ] = "Customer3"; // Give the Current column a value. tCust->Rows[ 0 ][ "Current" ] = true; tCust->Rows[ 1 ][ "Current" ] = true; tCust->Rows[ 2 ][ "Current" ] = false; // For each customer, create five rows in the Orders table. for ( int i = 1; i < 4; i++ ) { for ( int j = 1; j < 6; j++ ) { newRow2 = tOrders->NewRow(); newRow2[ "CustID" ] = i; newRow2[ "orderDate" ] = DateTime(2001,i,j * 2); newRow2[ "OrderAmount" ] = i * 10 + j * .1; // Add the row to the Orders table. tOrders->Rows->Add( newRow2 ); } } } }; int main() { Application::Run( gcnew Form1 ); }
import System.*; import System.ComponentModel.*; import System.Data.*; import System.Drawing.*; import System.Windows.Forms.*; public class Form1 extends System.Windows.Forms.Form { private System.ComponentModel.Container components; private Button button1; private Button button2; private DataGrid myDataGrid; private DataSet myDataSet; private boolean tablesAlreadyAdded; public Form1() { // Required for Windows Form Designer support. InitializeComponent(); // Call SetUp to bind the controls. SetUp(); } //Form1 protected void Dispose(boolean disposing) { if (disposing) { if (components != null) { components.Dispose(); } } super.Dispose(disposing); } //Dispose private void InitializeComponent() { // Create the form and its controls. this.components = new System.ComponentModel.Container(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.myDataGrid = new DataGrid(); this.set_Text("DataGrid Control Sample"); this.set_ClientSize(new System.Drawing.Size(450, 330)); button1.set_Location(new Point(24, 16)); button1.set_Size(new System.Drawing.Size(120, 24)); button1.set_Text("Change Appearance"); button1.add_Click(new System.EventHandler(button1_Click)); button2.set_Location(new Point(150, 16)); button2.set_Size(new System.Drawing.Size(120, 24)); button2.set_Text("Get Binding Manager"); button2.add_Click(new System.EventHandler(button2_Click)); myDataGrid.set_Location(new Point(24, 50)); myDataGrid.set_Size(new Size(300, 200)); myDataGrid.set_CaptionText("Microsoft DataGrid Control"); myDataGrid.add_MouseUp(new MouseEventHandler(Grid_MouseUp)); this.get_Controls().Add(button1); this.get_Controls().Add(button2); this.get_Controls().Add(myDataGrid); } //InitializeComponent public static void main(String[] args) { Application.Run(new Form1()); } //main private void SetUp() { // Create a DataSet with two tables and one relation. MakeDataSet(); /* Bind the DataGrid to the DataSet. The dataMember specifies that the Customers table should be displayed. */ myDataGrid.SetDataBinding(myDataSet, "Customers"); } //SetUp protected void button1_Click(Object sender, System.EventArgs e) { if (tablesAlreadyAdded) { return ; } AddCustomDataTableStyle(); } //button1_Click private void AddCustomDataTableStyle() { DataGridTableStyle ts1 = new DataGridTableStyle(); ts1.set_MappingName("Customers"); // Set other properties. ts1.set_AlternatingBackColor(Color.get_LightGray()); /* Add a GridColumnStyle and set its MappingName to the name of a DataColumn in the DataTable. Set the HeaderText and Width properties. */ DataGridColumnStyle boolCol = new DataGridBoolColumn(); boolCol.set_MappingName("Current"); boolCol.set_HeaderText("IsCurrent Customer"); boolCol.set_Width(150); ts1.get_GridColumnStyles().Add(boolCol); // Add a second column style. DataGridColumnStyle textCol = new DataGridTextBoxColumn(); textCol.set_MappingName("custName"); textCol.set_HeaderText("Customer Name"); textCol.set_Width(250); ts1.get_GridColumnStyles().Add(textCol); // Create the second table style with columns. DataGridTableStyle ts2 = new DataGridTableStyle(); ts2.set_MappingName("Orders"); // Set other properties. ts2.set_AlternatingBackColor(Color.get_LightBlue()); // Create new ColumnStyle objects DataGridColumnStyle cOrderDate = new DataGridTextBoxColumn(); cOrderDate.set_MappingName("OrderDate"); cOrderDate.set_HeaderText("Order Date"); cOrderDate.set_Width(100); ts2.get_GridColumnStyles().Add(cOrderDate); /* Use a PropertyDescriptor to create a formatted column. First get the PropertyDescriptorCollection for the data source and data member. */ PropertyDescriptorCollection pcol = this.get_BindingContext().get_Item(myDataSet, "Customers.custToOrders").GetItemProperties(); /* Create a formatted column using a PropertyDescriptor. The formatting character "c" specifies a currency format. */ DataGridColumnStyle csOrderAmount = new DataGridTextBoxColumn(pcol.get_Item("OrderAmount"), "c", true); csOrderAmount.set_MappingName("OrderAmount"); csOrderAmount.set_HeaderText("Total"); csOrderAmount.set_Width(100); ts2.get_GridColumnStyles().Add(csOrderAmount); /* Add the DataGridTableStyle instances to the GridTableStylesCollection. */ myDataGrid.get_TableStyles().Add(ts1); myDataGrid.get_TableStyles().Add(ts2); // Sets the tablesAlreadyAdded to true so this doesn't happen again. tablesAlreadyAdded = true; } //AddCustomDataTableStyle protected void button2_Click(Object sender, System.EventArgs e) { BindingManagerBase bmGrid; bmGrid = get_BindingContext().get_Item(myDataSet, "Customers"); MessageBox.Show(("Current BindingManager Position: " + bmGrid.get_Position())); } //button2_Click private void Grid_MouseUp(Object sender, MouseEventArgs e) { // Create a HitTestInfo object using the HitTest method. // Get the DataGrid by casting sender. DataGrid myGrid = ((DataGrid)(sender)); DataGrid.HitTestInfo myHitInfo = myGrid.HitTest(e.get_X(), e.get_Y()); Console.WriteLine(myHitInfo); Console.WriteLine(myHitInfo.get_Type()); Console.WriteLine(myHitInfo.get_Row()); Console.WriteLine(myHitInfo.get_Column()); } //Grid_MouseUp // Create a DataSet with two tables and populate it. private void MakeDataSet() { // Create a DataSet. myDataSet = new DataSet("myDataSet"); // Create two DataTables. DataTable tCust = new DataTable("Customers"); DataTable tOrders = new DataTable("Orders"); // Create two columns, and add them to the first table. DataColumn cCustID = new DataColumn("CustID", int.class.ToType()); DataColumn cCustName = new DataColumn("CustName"); DataColumn cCurrent = new DataColumn("Current" ,boolean.class.ToType()); tCust.get_Columns().Add(cCustID); tCust.get_Columns().Add(cCustName); tCust.get_Columns().Add(cCurrent); // Create three columns, and add them to the second table. DataColumn cID = new DataColumn("CustID", int.class.ToType()); DataColumn cOrderDate = new DataColumn( "orderDate", DateTime.class.ToType()); DataColumn cOrderAmount = new DataColumn("OrderAmount", System.Decimal.class.ToType()); tOrders.get_Columns().Add(cOrderAmount); tOrders.get_Columns().Add(cID); tOrders.get_Columns().Add(cOrderDate); // Add the tables to the DataSet. myDataSet.get_Tables().Add(tCust); myDataSet.get_Tables().Add(tOrders); // Create a DataRelation, and add it to the DataSet. DataRelation dr = new DataRelation("custToOrders", cCustID, cID); myDataSet.get_Relations().Add(dr); /* Populates the tables. For each customer and order, creates two DataRow variables. */ DataRow newRow1; DataRow newRow2; // Create three customers in the Customers Table. for (int i = 1; i < 4; i++) { newRow1 = tCust.NewRow(); newRow1.set_Item("custID", (System.Int32)i); // Add the row to the Customers table. tCust.get_Rows().Add(newRow1); } // Give each customer a distinct name. tCust.get_Rows().get_Item(0).set_Item("custName", "Customer1"); tCust.get_Rows().get_Item(1).set_Item("custName", "Customer2"); tCust.get_Rows().get_Item(2).set_Item("custName", "Customer3"); // Give the Current column a value. tCust.get_Rows().get_Item(0).set_Item("Current", (System.Boolean)true); tCust.get_Rows().get_Item(1).set_Item("Current", (System.Boolean)true); tCust.get_Rows().get_Item(2).set_Item("Current",(System.Boolean)false); // For each customer, create five rows in the Orders table. for (int i = 1; i < 4; i++) { for (int j = 1; j < 6; j++) { newRow2 = tOrders.NewRow(); newRow2.set_Item("CustID", (System.Int32)i); newRow2.set_Item("orderDate", new DateTime(2001, i, j * 2)); newRow2.set_Item("OrderAmount", (System.Single)(i * 10 + j * 0.1)); // Add the row to the Orders table. tOrders.get_Rows().Add(newRow2); } } } //MakeDataSet } //Form1

System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.DataGrid


Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


- DataGrid クラスのページへのリンク