DataGrid クラスとは? わかりやすく解説

DataGrid クラス

データ ソースの項目をテーブル表示するデータ連結リスト コントロールDataGrid コントロールにより、これらの項目の選択並べ替え編集できます

名前空間: System.Web.UI.WebControls
アセンブリ: System.Web (system.web.dll 内)
構文構文

Public Class DataGrid
    Inherits BaseDataList
    Implements INamingContainer
public class DataGrid : BaseDataList, INamingContainer
public ref class DataGrid : public
 BaseDataList, INamingContainer
public class DataGrid extends BaseDataList
 implements INamingContainer
public class DataGrid extends
 BaseDataList implements INamingContainer
解説解説

DataGrid コントロール使用してデータ ソースフィールドテーブルの列として表示しますDataGrid コントロール各行は、データ ソースレコード表しますDataGrid コントロール選択編集削除ページング並べ替えサポートしてます。

さまざまな列の型があり、それによってコントロール内の列の機能異なります使用できるさまざまな列型の一覧を次の表に示します

列型

説明

BoundColumn

データ ソースフィールド連結されている列を表示します。各項目はフィールドテキストとして表示されます。この型は DataGrid コントロール既定の列型です。

ButtonColumn

列の各項目に対してコマンド ボタン表示します。この列を使用して、[Add] ボタンや [Remove] ボタンなどのカスタム ボタン コントロールの列を作成できます

EditCommandColumn

列の各項目に対して編集コマンド格納されている列を表示します

HyperLinkColumn

列の各項目の内容ハイパーリンクとして表示します。列の内容は、データ ソースフィールドまたは静的テキスト連結できます

TemplateColumn

指定したテンプレートに従って、列の各項目を表示します。この機能により、列にカスタム コントロール作成できます

既定では AutoGenerateColumns プロパティtrue設定されています。つまり、データ ソース内のフィールドに対して BoundColumn オブジェクト作成されます。次に、各フィールドデータ ソース表示される順序DataGrid コントロールの列として表示されます。

また、AutoGenerateColumns プロパティfalse設定し開始および終了<Columns> タグで囲む列を一覧表示すると、どの列を DataGrid コントロール表示するかを手動制御できます指定した列が、一覧表順序Columns コレクション追加されます。この機能により、DataGrid コントロールの列をプログラムにより制御できます

ユーザー補助

使用例使用例

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 &lt;td&gt; and
 &lt;tr&gt; <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 &lt;td&gt; and &lt;tr&gt; <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 &lt;td&gt; and &lt;tr&gt; <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.Object
   System.Web.UI.Control
     System.Web.UI.WebControls.WebControl
       System.Web.UI.WebControls.BaseDataList
        System.Web.UI.WebControls.DataGrid
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
DataGrid メンバ
System.Web.UI.WebControls 名前空間
BaseDataList クラス
DataList
Repeater
BoundColumn クラス
ButtonColumn クラス
EditCommandColumn
HyperLinkColumn
TemplateColumn

DataGrid クラス

スクロールできるグリッドADO.NET データ表示します。DataGridView コントロールDataGrid コントロール後継であり、新し機能追加しますが、必要に応じて下位互換性および将来使用のために DataGrid コントロール保持することもできます

名前空間: System.Windows.Forms
アセンブリ: 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
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) */ 
/** @attribute ComVisibleAttribute(true) */ 
public class DataGrid extends Control implements
 ISupportInitialize, IDataGridEditingService
ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) 
ComVisibleAttribute(true) 
public class DataGrid extends
 Control implements ISupportInitialize, IDataGridEditingService
解説解説

System.Windows.Forms.DataGrid は、子テーブルへの Web似たリンクを表示します。リンクをクリックすると子テーブル移動できます。子テーブル表示されると、[戻る] ボタンキャプション表示されクリックすると親テーブルへ戻ることができます。親行からのデータは、キャプションの下と列ヘッダーの上表示されます。[戻る] ボタン右側にあるボタンクリックすると、親行の情報を非表示できます

実行時に、System.Windows.Forms.DataGridテーブル表示するには、SetDataBinding メソッド使用して DataSource プロパティと DataMember プロパティ有効なデータ ソース設定します有効なデータ ソース次に示します

DataSet クラス詳細については、ADO.NET での DataSet使用トピック参照してください

作成したグリッドで、ユーザーデータ編集できるが、新しい行を追加できないようにするには、DataViewデータ ソースとして使用し、AllowNew プロパティfalse設定します

データ ソースは BindingManagerBase オブジェクトによってさらに管理されます。データ ソースの各テーブルに対してフォームの BindingContext から BindingManagerBase返すことができます。たとえば、関連付けられた BindingManagerBase オブジェクトCount プロパティ返すと、データ ソースによって格納された行の数を確認できます

データ検証するには、データとそのイベント表している、基になるオブジェクト使用します。たとえば、データDataSetDataTable から発生している場合は、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 に追加します。たとえば、DataSource3 つの DataTable オブジェクト格納している DataSet設定されている場合は、3 つの DataGridTableStyle オブジェクトコレクションの各テーブル1 つ追加できますDataTable使用してDataGridTableStyle オブジェクト同期するには、DataGridTableStyle の MappingName を DataTable の TableName に設定しますオブジェクト配列へのバインド詳細については、DataGridTableStyle.MappingName プロパティトピック参照してください

テーブルカスタマイズされたビュー作成するには、DataGridTextBoxColumn クラスまたは DataGridBoolColumn クラスインスタンス作成しTableStyles プロパティ使用してアクセスされる GridTableStylesCollectionオブジェクト追加します。このクラス両方とも、DataGridColumnStyle から継承します。各列スタイルに対して、MappingName を、グリッド表示する列の ColumnName に設定します。列を非表示にするには、MappingName有効な ColumnName 以外の値に設定します

列のテキスト書式指定するには、DataGridTextBoxColumnFormat プロパティを、日付と時刻書式指定文字列 または 標準数値書式指定文字列 の値のいずれかに設定します

DataGridオブジェクト厳密に指定され配列バインドするには、オブジェクト型パブリック プロパティ含まれている必要があります配列表示する DataGridTableStyle作成するには、DataGridTableStyle.MappingName プロパティtypename[]設定します。なお、この typename実際オブジェクト型名に置き換えてくださいまた、MappingName プロパティでは大文字と小文字区別されることに注意してください。型の名前は正確に指定する必要があります例については、MappingName プロパティトピック参照してください

また、DataGridArrayListバインドできますArrayList特長は、複数の型のオブジェクト格納できることです。ただし、DataGridリスト内のすべての項目の型が 1 番目の項目の型と同じ場合限りリストバインドできます。つまり、すべてのオブジェクトの型が同じであるか、リスト内の最初の項目と同じクラスからすべてのクラス継承している必要があります。たとえば、リスト内の最初の項目が Control場合2 番目の項目は (Control から継承した) TextBoxできます逆に、1 番目の項目が TextBox場合2 番目のオブジェクトControl になることはできません。さらに、ArrayList は、バインディングするときは、項目を含んでいる必要があります。空の ArrayList場合、空のグリッドとなります。さらに、ArrayListオブジェクトにはパブリック プロパティ含まれている必要がありますArrayListバインディングするときは、DataGridTableStyleMappingName を "ArrayList" (型の名前) に設定します

DataGridTableStyle では、System.Windows.Forms.DataGrid コントロール設定オーバーライドする、色とキャプション属性設定できます。ただし、これらのプロパティ設定されていない場合は、コントロール設定には既定設定使用されます。DataGridTableStyle プロパティオーバーライドできるプロパティ次に示します

  • AllowSorting

  • AlternatingBackColor

  • BackColor

  • ColumnHeadersVisible

  • ForeColor

  • GridLineColor

  • GridLineStyle

  • HeaderBackColor

  • HeaderFont

  • HeaderForeColor

  • LinkColor

  • PreferredColumnWidth

  • PreferredRowHeight

  • ReadOnly

  • RowHeadersVisible

  • RowHeaderWidth

  • SelectionBackColor

  • SelectionForeColor

各列の外観カスタマイズするには、DataGridColumnStyle オブジェクトを各 DataGridTableStyle の GridColumnStyles プロパティ通じてアクセスする GridColumnStylesCollection追加しますDataTableDataColumn使用してDataGridColumnStyle同期するには、MappingNameDataColumnColumnName設定しますDataGridColumnStyle構築するときは、列データ表示方法指定する書式指定文字列設定することもできます。たとえば、テーブル格納されている日付を列で表示するときに、短い日付書式使用するように指定できます

注意に関するメモメモ

DataGridView コントロールDataGrid コントロール後継であり、新し機能追加しますが、必要に応じて下位互換性および将来使用のために DataGrid コントロール保持することもできます詳細については、「Windows フォームの DataGridView コントロールと DataGrid コントロール違いについて」を参照してください

使用例使用例

Windows フォーム2 つDataTable オブジェクト格納する DataSet、および 2 つテーブル関連付ける DataRelation を作成するコード例次に示します。さらに、データ表示するために SetDataBinding メソッド通じてSystem.Windows.Forms.DataGrid コントロールDataSetバインドされますフォームボタン変更してグリッド外観変更するには、2 つDataGridTableStyle オブジェクト作成し、各オブジェクトMappingNameDataTable オブジェクトいずれか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.Object
   System.MarshalByRefObject
     System.ComponentModel.Component
       System.Windows.Forms.Control
        System.Windows.Forms.DataGrid
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「DataGrid クラス」の関連用語











DataGrid クラスのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



DataGrid クラスのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2025 Microsoft.All rights reserved.

©2025 GRAS Group, Inc.RSS