Export (0) Print
Expand All

DataGrid Class

Displays ADO.NET data in a scrollable grid.

For a list of all members of this type, see DataGrid Members.

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

[Visual Basic]
Public Class DataGrid
   Inherits Control
   Implements ISupportInitialize
[C#]
public class DataGrid : Control, ISupportInitialize
[C++]
public __gc class DataGrid : public Control, ISupportInitialize
[JScript]
public class DataGrid extends Control implements ISupportInitialize

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Remarks

The System.Windows.Forms.DataGrid displays Web-like links to child tables. You can click on a link to navigate to the child table. When a child table is displayed, a back button appears in the caption that can be clicked to navigate back to the parent table. The data from the parent rows is displayed below the caption and above the column headers. You can hide the parent row information by clicking the button to the right of the back button.

To display a table in the System.Windows.Forms.DataGrid at run time, use the SetDataBinding method to set the DataSource and DataMember properties to a valid data source. The following data sources are valid:

For more information about the DataSet class, see Creating and Using DataSets.

You can create a grid that allows users to edit data but prevents them from adding new rows by using a DataView as the data source and setting the AllowNew property to false.

Data sources are further managed by BindingManagerBase objects. For each table in a data source, a BindingManagerBase can be returned from the form's BindingContext. For example, you can determine the number of rows contained by a data source by returning the associated BindingManagerBase object's Count property.

To validate data, use the underlying objects that represent data and their events. For example, if the data comes from a DataTable in a DataSet, use the ColumnChanging and RowChanging events.

Note   Because the number of columns can be customized (by adding or deleting members of the GridColumnStylesCollection) and the rows can be sorted by column, the RowNumber and ColumnNumber property values cannot be guaranteed to correspond to DataRow and DataColumn indexes in a DataTable. Therefore you should avoid using those properties in the Validating event to validate data.

To determine which cell is selected, use the CurrentCell property. Change the value of any cell by using the Item property, which can take either the row and column indexes of the cell, or a single DataGridCell. Monitor the CurrentCellChanged event to detect when the user selects another cell.

To determine which part of the control the user clicked, use the HitTest method in the MouseDown event. The HitTest method returns a DataGrid.HitTestInfo object, which contains the row and column of a clicked area.

To manage the appearance of the control at run time, several properties for setting the color and caption attributes are available, including the CaptionForeColor, CaptionBackColor, CaptionFont, and so on.

The appearance of the displayed grid (or grids) can be further modified by creating DataGridTableStyle objects and adding them to the GridTableStylesCollection, which is accessed through the TableStyles property. For example, if the DataSource is set to a DataSet containing three DataTable objects, you can add three DataGridTableStyle objects to the collection, one for each table. To synchronize each DataGridTableStyle object with a DataTable, set the MappingName of the DataGridTableStyle to the TableName of the DataTable. For more information about binding to an array of objects, see the DataGridTableStyle.MappingName property.

To create a customized view of a table, create an instance of a DataGridTextBoxColumn or DataGridBoolColumn class and add the object to the GridTableStylesCollection accessed through the TableStyles property. Both classes inherit from DataGridColumnStyle. For each column style, set the MappingName to the ColumnName of a column that you want to show in the grid. To hide a column, set its MappingName to something other than a valid ColumnName.

To format the text of a column, set the Format property of the DataGridTextBoxColumn to one of the values found in Date and Time Format Strings or Standard Numeric Format Strings.

To bind the DataGrid to a strongly typed array of objects, the object must contain public properties. To create a DataGridTableStyle that displays such an array, set the DataGridTableStyle.MappingName property to classname[] where classname is replaced by the class name. Also note that the MappingName property is case-sensitive. See the MappingName property for an example.

You can also bind the DataGrid to an ArrayList. A feature of the ArrayList is that it can contain objects of multiple types, but the DataGrid can only bind to such a list when all items in the list are of the same type as the first item. This means that all objects must either be of the same type, or they must inherit from the same class as the first item in the list. For example, if the first item in a list is a Control, the second item could be a TextBox (which inherits from Control). If, on the other hand, the first item is a TextBox, the second object cannot be a Control. Further, the ArrayList must have items in it when it is bound. An empty ArrayList will result in an empty grid. When binding to an ArrayList, set the MappingName of the DataGridTableStyle to "ArrayList" (the type name).

For each DataGridTableStyle, you can set color and caption attributes that override the settings for the System.Windows.Forms.DataGrid control. However, if those properties are not set, the settings for the control are used by default. The following properties can be overridden by DataGridTableStyle properties:

To customize the appearance of individual columns, add DataGridColumnStyle objects to the GridColumnStylesCollection, which is accessed through the GridColumnStyles property of each DataGridTableStyle. To synchronize each DataGridColumnStyle with a DataColumn in the DataTable, set the MappingName to the ColumnName of a DataColumn. When constructing a DataGridColumnStyle, you can also set a formatting string that specifies how the column displays data. For example, you can specify that the column use a short-date format to display dates contained in the table.

CAUTION   Always create DataGridColumnStyle objects and add them to the GridColumnStylesCollection before adding DataGridTableStyle objects to the GridTableStylesCollection. When you add an empty DataGridTableStyle to the collection, DataGridColumnStyle objects are automatically generated for you. Consequently, an exception will be thrown if you try to add new DataGridColumnStyle objects with duplicate MappingName values to the GridColumnStylesCollection.

Example

The following example creates a Windows form, a DataSet containing two DataTable objects, and a DataRelation that relates the two tables. To display the data, a System.Windows.Forms.DataGrid control is then bound to the DataSet through the SetDataBinding method. A button on the form changes the appearance of the grid by creating two DataGridTableStyle objects and setting the MappingName of each object to a TableName of one of the DataTable objects. The example also contains code in the MouseUp event that uses the HitTest method to print the column, row, and part of the grid that has been clicked.

[Visual Basic] 
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.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
      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 
        
   Protected Sub button1_Click(sender As Object, 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 
    
   Protected Sub button2_Click(sender As Object, 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 

[C#] 
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.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      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");
   }

   protected 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;
   }

   protected 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);
         }
      }
   }
}

[C++] 
#using <mscorlib.dll>
#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 __gc class Form1 : public System::Windows::Forms::Form {
private:
    System::ComponentModel::Container __gc *components;
    Button __gc *button1;
    Button __gc *button2;
    DataGrid __gc *myDataGrid;   
    DataSet __gc *myDataSet;
    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();
            }
        }
        __super::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->AutoScaleBaseSize = System::Drawing::Size(5, 13);
        this->Text = S"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 = S"Change Appearance";
        button1->Click += new System::EventHandler(this, &Form1::button1_Click);

        button2->Location = System::Drawing::Point(150, 16);
        button2->Size = System::Drawing::Size(120, 24);
        button2->Text = S"Get Binding Manager";
        button2->Click += new System::EventHandler(this, &Form1::button2_Click);

        myDataGrid->Location = System::Drawing::Point(24, 50);
        myDataGrid->Size = System::Drawing::Size(300, 200);
        myDataGrid->CaptionText = S"Microsoft DataGrid Control";
        myDataGrid->MouseUp += new 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, S"Customers");
    };

protected:
    void button1_Click(Object *sender, System::EventArgs *e) {
      if (TablesAlreadyAdded) return;
      AddCustomDataTableStyle();
    };

private:
    void AddCustomDataTableStyle() {
        DataGridTableStyle __gc *ts1 = new DataGridTableStyle();
        ts1->MappingName = S"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 __gc *boolCol = new DataGridBoolColumn();
        boolCol->MappingName = S"Current";
        boolCol->HeaderText = S"IsCurrent Customer";
        boolCol->Width = 150;
        ts1->GridColumnStyles->Add(boolCol);
      
        // Add a second column style.
        DataGridColumnStyle __gc *TextCol = new DataGridTextBoxColumn();
        TextCol->MappingName = S"custName";
        TextCol->HeaderText = S"Customer Name";
        TextCol->Width = 250;
        ts1->GridColumnStyles->Add(TextCol);

        // Create the second table style with columns.
        DataGridTableStyle __gc *ts2 = new DataGridTableStyle();
        ts2->MappingName = S"Orders";

        // Set other properties.
        ts2->AlternatingBackColor = Color::LightBlue;
      
        // Create new ColumnStyle objects
        DataGridColumnStyle __gc *cOrderDate = new DataGridTextBoxColumn();
        cOrderDate->MappingName = S"OrderDate";
        cOrderDate->HeaderText = S"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 __gc *pcol = this->BindingContext->get_Item(myDataSet, S"Customers.custToOrders")->GetItemProperties();
 
        /* Create a formatted column using a PropertyDescriptor.
        The formatting character "c" specifies a currency format. */     
        DataGridColumnStyle __gc *csOrderAmount = new DataGridTextBoxColumn(pcol->Item[S"OrderAmount"], S"c", true);
        csOrderAmount->MappingName = S"OrderAmount";
        csOrderAmount->HeaderText = S"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;
    };

protected:
    void button2_Click(Object *sender, System::EventArgs *e) {
        BindingManagerBase __gc *bmGrid;
        bmGrid = BindingContext->get_Item(myDataSet, S"Customers");
        MessageBox::Show(String::Concat(S"Current BindingManager Position: ", __box(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 __gc *myGrid = dynamic_cast<DataGrid *>(sender);
        DataGrid::HitTestInfo __gc *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 = new DataSet(S"myDataSet");
      
        // Create two DataTables.
        DataTable __gc *tCust = new DataTable(S"Customers");
        DataTable __gc *tOrders = new DataTable(S"Orders");

        // Create two columns, and add them to the first table.
        DataColumn __gc *cCustID = new DataColumn(S"CustID", __typeof(__int32));
        DataColumn __gc *cCustName = new DataColumn(S"CustName");
        DataColumn __gc *cCurrent = new DataColumn(S"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 __gc *cID = new DataColumn(S"CustID", __typeof(__int32));
        DataColumn __gc *cOrderDate = new DataColumn(S"orderDate", __typeof(DateTime));
        DataColumn __gc *cOrderAmount = new DataColumn(S"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 __gc *dr = new DataRelation(S"custToOrders", cCustID , cID);
        myDataSet->Relations->Add(dr);
   
        /* Populate the tables. For each customer and order, 
        create need two DataRow variables. */
        DataRow __gc *newRow1;
        DataRow __gc *newRow2;

        // Create three customers in the Customers Table.
        for (int i = 1; i < 4; i++) {
            newRow1 = tCust->NewRow();
            newRow1->Item[S"custID"] = __box(i);
            // Add the row to the Customers table.
            tCust->Rows->Add(newRow1);
        }
        // Give each customer a distinct name.
        tCust->Rows->Item[0]->Item[S"custName"] = S"Customer1";
        tCust->Rows->Item[1]->Item[S"custName"] = S"Customer2";
        tCust->Rows->Item[2]->Item[S"custName"] = S"Customer3";

        // Give the Current column a value.
        tCust->Rows->Item[0]->Item[S"Current"] = __box(true);
        tCust->Rows->Item[1]->Item[S"Current"] = __box(true);
        tCust->Rows->Item[2]->Item[S"Current"] = __box(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->Item[S"CustID"]= __box(i);
                newRow2->Item[S"orderDate"]= __box(DateTime(2001, i, j * 2));
                newRow2->Item[S"OrderAmount"] = __box(i * 10 + j  * .1);
                // Add the row to the Orders table.
                tOrders->Rows->Add(newRow2);
            }
        }
    };
};

int main() {
    Application::Run(new Form1());
}

[JScript] 
import System;
import System.ComponentModel;
import System.Data;
import System.Drawing;
import System.Windows.Forms;

public class Form1 extends System.Windows.Forms.Form
{
   private var components : System.ComponentModel.Container;
   private var button1 : Button;
   private var button2 : Button;
   private var myDataGrid : DataGrid;   
   private var myDataSet : DataSet;
   private var TablesAlreadyAdded : Boolean;
   public function Form1()
   {
      // Required for Windows Form Designer support.
      InitializeComponent();
      // Call SetUp to bind the controls.
      SetUp();
   }

   protected override function Dispose(disposing :  Boolean){
      if( disposing ){
         if (components != null){
            components.Dispose();}
      }
      super.Dispose( disposing );
   }
   private function 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.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      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.add_Click(button1_Click);

      button2.Location = new Point(150, 16);
      button2.Size = new System.Drawing.Size(120, 24);
      button2.Text = "Get Binding Manager";
      button2.add_Click(button2_Click);

      myDataGrid.Location = new  Point(24, 50);
      myDataGrid.Size = new System.Drawing.Size(300, 200);
      myDataGrid.CaptionText = "Microsoft DataGrid Control";
      myDataGrid.add_MouseUp(Grid_MouseUp);
      
      this.Controls.Add(button1);
      this.Controls.Add(button2);
      this.Controls.Add(myDataGrid);
   }

   public static function Main()
   {
      Application.Run(new Form1());
   }
   
   private function 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");
   }

   protected function button1_Click(sender : Object, e : System.EventArgs)
   {
      if(TablesAlreadyAdded) return;
      AddCustomDataTableStyle();
   }

   private function AddCustomDataTableStyle()
   {
      var ts1 : DataGridTableStyle = 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. */
      
      var boolCol : DataGridColumnStyle = new DataGridBoolColumn();
      boolCol.MappingName = "Current";
      boolCol.HeaderText = "IsCurrent Customer";
      boolCol.Width = 150;
      ts1.GridColumnStyles.Add(boolCol);
      
      // Add a second column style.
      var TextCol : DataGridColumnStyle = new DataGridTextBoxColumn();
      TextCol.MappingName = "custName";
      TextCol.HeaderText = "Customer Name";
      TextCol.Width = 250;
      ts1.GridColumnStyles.Add(TextCol);

      // Create the second table style with columns.
      var ts2 : DataGridTableStyle = new DataGridTableStyle();
      ts2.MappingName = "Orders";

      // Set other properties.
      ts2.AlternatingBackColor = Color.LightBlue;
      
      // Create new ColumnStyle objects
      var cOrderDate : DataGridColumnStyle = 
      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. */
      var pcol : PropertyDescriptorCollection = this.BindingContext
      [myDataSet, "Customers.custToOrders"].GetItemProperties();
 
      /* Create a formatted column import a PropertyDescriptor.
      The formatting character "c" specifies a currency format. */     
      var csOrderAmount : DataGridColumnStyle = 
      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;
   }

   protected function button2_Click(sender : Object, e : System.EventArgs)
   {
      var bmGrid : BindingManagerBase;
      bmGrid = BindingContext[myDataSet, "Customers"];
      MessageBox.Show("Current BindingManager Position: " + bmGrid.Position);
   }

   private function Grid_MouseUp(sender : Object, e : MouseEventArgs)
   {
      // Create a HitTestInfo object import the HitTest method.

      // Get the DataGrid by casting sender.
      var myGrid : DataGrid = DataGrid(sender);
      var myHitInfo : DataGrid.HitTestInfo= 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 function MakeDataSet()
   {
      // Create a DataSet.
      myDataSet = new DataSet("myDataSet");
      
      // Create two DataTables.
      var tCust : DataTable = new DataTable("Customers");
      var tOrders : DataTable = new DataTable("Orders");

      // Create two columns, and add them to the first table.
      var cCustID : DataColumn = new DataColumn("CustID", int);
      var cCustName : DataColumn = new DataColumn("CustName");
      var cCurrent : DataColumn = new DataColumn("Current", Boolean);
      tCust.Columns.Add(cCustID);
      tCust.Columns.Add(cCustName);
      tCust.Columns.Add(cCurrent);

      // Create three columns, and add them to the second table.
      var cID : DataColumn = 
      new DataColumn("CustID", int);
      var cOrderDate : DataColumn = 
      new DataColumn("orderDate", DateTime);
      var cOrderAmount : DataColumn = 
      new DataColumn("OrderAmount", 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.
      var dr : DataRelation = new DataRelation
      ("custToOrders", cCustID , cID);
      myDataSet.Relations.Add(dr);
   
      /* Populates the tables. For each customer and order, 
      creates two DataRow variables. */
      var newRow1 : DataRow;
      var newRow2 : DataRow;

      // Create three customers in the Customers Table.
      for(var x : int = 1; x < 4; x++)
      {
         newRow1 = tCust.NewRow();
         newRow1["custID"] = x;
         // 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(var i : int = 1; i < 4; i++)
      {
         for(var j : int = 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);
         }
      }
   }
}

Form1.Main();

Requirements

Namespace: System.Windows.Forms

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

Assembly: System.Windows.Forms (in System.Windows.Forms.dll)

See Also

DataGrid Members | System.Windows.Forms Namespace | Accessing Data with ADO.NET | DataSet | DataView | DataTable | DataRow

Show:
© 2014 Microsoft