How To Use Visual Basic .NET to Format a Windows Forms DataGrid That Is Bound to an Array

Article translations Article translations
Article ID: 317383 - View products that this article applies to.
This article was previously published under Q317383
Expand all | Collapse all

On This Page

SUMMARY

You can bind Visual Studio .NET controls not only to traditional data sources such as a DataTable object, but also to other types of lists, such as an array. However, when you bind a DataGrid control to an array, the array columns appear unformatted and in seemingly random order.

This step-by-step article describes how you can use the DataGridTableStyles and the DataGridColumnStyles collections to specify column order and formatting for the array columns that appear in your DataGrid control.

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Windows XP Professional, Microsoft Windows 2000 Professional, Microsoft Windows 2000 Server, Microsoft Windows 2000 Advanced Server, or Microsoft Windows NT 4.0 Server
  • Microsoft Visual Studio .NET
This article assumes that you are familiar with the following topics:
  • Microsoft Visual Basic .NET

Create the Windows Application in Visual Basic .NET

  1. Start Visual Studio .NET.
  2. On the File menu, point to New, and then click Project.
  3. In the New Project dialog box, click Visual Basic Projects under Project Types, and then click Windows Application under Templates.
  4. Drag one DataGrid control and two Button controls from the toolbox onto the default form, Form1.vb.
  5. In the Properties window, change the Text property of the first Button control to Bind. Change the Text property of the second Button control to Format.
  6. Switch to Code view, and then add the following code to the very top of the form's code module:
    Imports System.ComponentModel
    					

Create a Class for the Array

You can only bind a DataGrid to a one-dimensional array. To display multiple columns of information, you must create a class or a structure (user-defined type) with multiple members, and then use an array of instances of this class or structure.
  1. At the very bottom of the form's code module, after the End Class statement for the form class, add the following code to insert a TestItem class that has a constructor and four properties:
    Public Class TestItem
    
        Private m_TestID As Integer
        Private m_TestName As String
        Private m_TestBool As String
        Private m_TestAmount As Double
    
        Public ReadOnly Property TestID()
            Get
                TestID = m_TestID
            End Get
        End Property
    
        Public ReadOnly Property TestName()
            Get
                TestName = m_TestName
            End Get
        End Property
    
        Public ReadOnly Property TestBool()
            Get
                TestBool = m_TestBool
            End Get
        End Property
    
        Public ReadOnly Property TestAmount()
            Get
                TestAmount = m_TestAmount
            End Get
        End Property
    
        Public Sub New(ByVal TestID As Integer, ByVal TestName As String, ByVal TestBool As String, ByVal TestAmount As Double)
            Me.m_TestID = TestID
            Me.m_TestName = TestName
            Me.m_TestBool = TestBool
            Me.m_TestAmount = TestAmount
        End Sub
    
    End Class
    						
    The four properties of this class become four columns in the bound DataGrid.
  2. At the top of the form's class code, add the following array declaration to create an empty array of 6 (0 to 5) TestItem objects:
        Dim TestItems() As TestItem = New TestItem(5) {}
    					

Add the Binding Code

  1. In Design view, double-click Bind to add an event handler to the button.
  2. Add the following code to the Button1_Click event to create the six array items:
            TestItems(0) = New TestItem(1, "John", "true", 1000)
            TestItems(1) = New TestItem(2, "Julia", "false", 2000)
            TestItems(2) = New TestItem(3, "Michael", "true", 3000)
            TestItems(3) = New TestItem(4, "Laura", "false", 4000)
            TestItems(4) = New TestItem(5, "Alan", "true", 5000)
            TestItems(5) = New TestItem(6, "Susan", "true", 6000)
    					
  3. Add the following code to bind the array to the DataGrid:
            DataGrid1.DataSource = TestItems
    					

Add the Formatting Code

  1. To format the array data in the bound DataGrid, you must first create a new DataGridTableStyle object. In Design view, double-click Format to add an event handler to the button, and then add the following code in the Button2_Click event:
            Dim gs As DataGridTableStyle = New DataGridTableStyle()
    					
  2. Add the following code to map the DataGridTableStyle to the array of TestItem objects:
            gs.MappingName = TestItems.GetType().Name
    						
    The MappingName property is the crucial information in each DataGridTableStyle and DataGridColumnStyle object. MappingName maps each grid column to one of the properties of the class, and then maps the grid as a whole to the array.
  3. Add the following code to display the ID and Name columns as DataGridTextBoxColumns objects:
            Dim cs As DataGridTextBoxColumn = New DataGridTextBoxColumn()
            cs.MappingName = "TestID"
            cs.HeaderText = "Test ID"
            cs.Alignment = HorizontalAlignment.Center
            cs.Width = 50
            gs.GridColumnStyles.Add(cs)
    
            cs = New DataGridTextBoxColumn()
            cs.MappingName = "TestName"
            cs.HeaderText = "Test Name"
            cs.Alignment = HorizontalAlignment.Left
            cs.Width = 75
            gs.GridColumnStyles.Add(cs)
    					
  4. Add the following code to display the true/false TestBool column as a DataGridBoolColumn object, which is displayed by using check boxes:
            Dim cs2 As DataGridBoolColumn = New DataGridBoolColumn()
            cs2.MappingName = "TestBool"
            cs2.HeaderText = "Test Bool"
            cs2.Width = 75
            cs2.TrueValue = "true"
            cs2.FalseValue = "false"
            gs.GridColumnStyles.Add(cs2)
    					
  5. Use the PropertyDescriptor object (from the System.ComponentModel class) to display the Amount column and to format its values as currency:
            Dim cm As CurrencyManager = CType(Me.BindingContext(TestItems), CurrencyManager)
            Dim pd As PropertyDescriptor = cm.GetItemProperties()("TestAmount")
    
            cs = New DataGridTextBoxColumn(pd, "c")
            cs.MappingName = "TestAmount"
            cs.HeaderText = "Test Amount"
            cs.Alignment = HorizontalAlignment.Right
            cs.Width = 75
            gs.GridColumnStyles.Add(cs)
    					
  6. Add the following code to add the DataGridTableStyle object to the TableStyles collection of the DataGrid:
            DataGrid1.TableStyles.Add(gs)
    					
You can also configure the TableStyles and the ColumnStyles visually by using the Visual Studio Collection Editor. To do this, follow the steps below using the Editor replace coding in previous steps 1-5:
  1. Click the DataGrid on the form.
  2. In the Properties window, click the TableStyles property, and then click the ellipsis (...).
  3. In the DataGridTableStyle Collection Editor dialog box, add a TableStyle, and then click OK.
  4. In the Properties window, click the GridColumnStyles property, and then click the ellipsis.
  5. In the DataGridColumnStyle Collection Editor dialog box, add add ColumnStyles for each of the 4 array item properties, and then click OK. for each of the 4 array item properties, and then click OK.
  6. In Column Properties, enter Test ID for HeaderText and testid for MappingName.
  7. Repeat this step for the testname, testbool, and testamount fields. However, when you add the testbool column, select DataGridBoolColumn from the drop-down list box to the right of the Add button. (The other columns are all DataGridTextBoxColumns.)
  8. Click OK to dismiss all dialog boxes.
  9. Add the following code to add the DataGridTableStyle object to the TableStyles collection of the DataGrid:
            DataGrid1.TableStyles.Add(gs)
    						
NOTE: When you bind to an array, you must ensure that the MappingName property for the DataGridTableStyle is blank in the Collection Editor and then specify MappingName in your code as follows:
        DataGridTableStyle1.MappingName = TestItems.GetType().Name
				

Run the Project

  1. Run the project.
  2. Click Bind to load the array into the DataGrid. Notice that the columns appear out of order and that the data appears unformatted.
  3. Click Format to apply the DataGridTableStyle to the DataGrid. Notice that the columns now appear in the expected order and that the data is formatted by using the appropriate styles.

Troubleshooting

  • If you do use the DataGridTableStyle, you must define a DataGridColumnStyle for every column that appears in the grid. You cannot define styles for some columns and display others by using the default settings.
  • When you set the Alignment property in the DataGridColumnStyle, you affect the HeaderText property, as well as the data in the column.
  • The DataGrid.TableStyles Property documentation states:
    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.

REFERENCES

For more information about the DataGrid control, search for "DataGrid Control" and "DataGrid Class" on MSDN.

Properties

Article ID: 317383 - Last Review: May 23, 2005 - Revision: 2.8
APPLIES TO
  • Microsoft Visual Studio .NET 2003 Enterprise Architect
  • Microsoft Visual Studio .NET 2003 Enterprise Developer
  • Microsoft Visual Studio .NET 2003 Academic Edition
  • Microsoft Visual Studio .NET 2002 Professional Edition
  • Microsoft Visual Studio .NET 2002 Enterprise Architect
  • Microsoft Visual Studio .NET 2002 Enterprise Developer
  • Microsoft Visual Studio .NET 2002 Academic Edition
Keywords: 
kbdatabinding kbhowtomaster KB317383

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com