How to bind a DataGrid control to an ArrayList of objects or structures by using Visual C++ .NET or Visual C++ 2005

Article translations Article translations
Article ID: 816164 - View products that this article applies to.
Expand all | Collapse all

On This Page

SUMMARY

This step-by-step article describes how to bind an ArrayList class of objects to a DataGrid control. The example includes a Windows form with a DataGrid control to display object property values and includes four command buttons to browse the rows of the DataGrid control.

Requirements

This article assumes that you are familiar with the following topics:
  • Visual C++ .NET or Visual C++ 2005 programming concepts
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Visual C++ .NET or Microsoft Visual C++ 2005

Design of the Class

To bind a class to a control, the class must have property accessors. Any property that you bind must have a getter function and a setter function. You implement properties by using the getter function and the setter function, and you notify the compiler that these are property functions that use the __property keyword. The sample class that is used in this article has three members:
__gc class Guitar
{
private:
        String *make;
        String *model;
        short year;
public:
    Guitar(void);
    ~Guitar(void);
        
        Guitar(String *strMake, String *strModel, short shYear)
        {
            make = strMake;
            model = strModel;
            year = shYear;
        }

        __property String* get_Make() 
        {
            return make; 
        }
        __property void set_Make(String* val)
        {
            make = (val); 
        }
        __property String* get_Model()
        { 
            return model; 
        }
        __property void set_Model(String* val)
        {
            model = (val); 
        }

        __property short get_Year()
        { 
            return year; 
        }
        __property void set_Year(short shValue)
        {
            year = shValue; 
        }
};

Add Class Instances to an ArrayList

To create instances and add them to the ArrayList class, follow these steps:
  1. Declare an ArrayList class as follows:
    private: ArrayList *arrayList;
  2. In the FormLoad event handler, create instances of the class, and then add the instances to the ArrayList class as follows:
    //Create an ArrayList.
    arrayList = new ArrayList();
    
    //Populate the array list.
    arrayList->Add(new guitar(S"GibSon",S"Les Paul",1958));
    arrayList->Add(new guitar(S"Fender",S"Jazz Bass",1958));
    arrayList->Add(new guitar(S"Guild",S"Bluesbird",1958));
    

Bind the ArrayList to the DataGrid

After the ArrayList class is populated, set the DataSource property of the DataGrid control to the ArrayList class. The columns in the DataGrid control are populated based on the properties for which in-scope property accessors exist.
// Bind the Array List to DataGrid.
      dataGrid1->DataSource = arrayList;

Move Through the ArrayList

You can use the CurrencyManager class to move through the ArrayList class. To do this, declare a variable for the CurrencyManager class as follows:
private: CurrencyManager *currencyManager;
Associate the CurrencyManager class with the BindingContext function of the control (in this case, the ArrayList).
currencyManager = (CurrencyManager*)dataGrid1->BindingContext
->Item[arrayList];
The CurrencyManager class has a Position property that you can manipulate to iterate over the members of the ArrayList class. By adding to, or subtracting from, the current value of the Position function, you can move through the rows of the DataGrid control.
//Move forward one element.
currencyManager.Position++;
//Move back one element.
currencyManager.Position--;
//Move to the beginning.
currencyManager.Position = 0;
//Move to the end.
currencyManager.Position = arrayList.Count - 1;
				

Step-by-Step Example

  1. Start Microsoft Visual Studio .NET 2003 or Microsoft Visual Studio 2005.
  2. On the File menu, point to New, and then click Project.
  3. Click Visual C++ Projects under Project Types, and then click Windows Forms Application (.NET) under Templates.

    Note In Visual Studio 2005, click Visual C++ under Project Types, and then click Windows Forms Application under Templates.
  4. In the Name text box, type Q816164, and then click OK.
  5. In Solution Explorer, switch to Class View. To do this, click Class View on the View menu.
  6. Right-click Q816164, point to Add, and then click Add Class.
  7. In the Add Class dialog box, click Generic C++ Class under Templates, and then click Open.

    Note In Visual Studio 2005, click C++ Cass under Templates, and then click Add.
  8. In the Generic C++ Class Wizard, type Guitar in the Class name text box, and then click Finish. The Guitar class appears as follows:
    #pragma once
    
    class Guitar
    {
    public:
    	Guitar(void);
    	~Guitar(void);
    };
    
    Note In Visual Studio 2005, the code is as follows.
    #pragma once
    
    ref class Guitar
    {
    public:
    	Guitar(void);
    };
    
    To make the Guitar class a Managed Extensions for C++ class, add the __gc keyword before the Guitar class, as follows:
    __gc class Guitar
    {
    public:
    	Guitar(void);
    	~Guitar(void);
    };
    
  9. Replace the existing code in the Guitar.h file with the following code:
    #pragma once
    
    using namespace System;
    __gc class Guitar
    {
    private:
            String *make;
            String *model;
            short year;
    public:
        Guitar(void);
        ~Guitar(void);
            
            Guitar(String *strMake, String *strModel, short shYear)
            {
                make = strMake;
                model = strModel;
                year = shYear;
            }
    
            __property String* get_Make() 
            {
                return make; 
            }
            __property void set_Make(String* val)
            {
                make = (val); 
            }
            __property String* get_Model()
            { 
                return model; 
            }
            __property void set_Model(String* val)
            {
                model = (val); 
            }
    
            __property short get_Year()
            { 
                return year; 
            }
            __property void set_Year(short shValue)
            {
                year = shValue; 
            }
    };
    
    
    Note You must add the common language runtime support compiler option (/clr:oldSyntax) in Visual C++ 2005 to successfully compile the previous code sample. To add the common language runtime support compiler option in Visual C++ 2005, follow these steps:
    1. Click Project, and then click <ProjectName> Properties.

      Note <ProjectName> is a placeholder for the name of the project.
    2. Expand Configuration Properties, and then click General.
    3. Click to select Common Language Runtime Support, Old Syntax (/clr:oldSyntax) in the Common Language Runtime support project setting in the right pane, click Apply, and then click OK.
    For more information about the common language runtime support compiler option, visit the following Microsoft Web site:
    /clr (Common Language Runtime Compilation)
    http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspx
  10. Close the Guitar.h code window, and then switch to Form Designer.
  11. Add a DataGrid control to Form1. Size the DataGrid control to fit four columns and three rows.
  12. Add four Button controls to Form1, and then arrange the buttons horizontally.
  13. Change the Text property of Button1 to Next.
  14. Change the Text property of Button2 to Previous.
  15. Change the Text property of Button3 to First.
  16. Change the Text property of Button4 to Last.
  17. Open the Form1.h file, and add the following code at the beginning:
    #include "Guitar.h"
  18. Add the following code to the Form1 class:
    private: System::Collections::ArrayList *arrayList;	
    private: System::Windows::Forms::CurrencyManager *currencyManager;	
    
  19. Switch to Form Designer, right-click form1, and then click Properties.
  20. Click the Events icon, and then double-click the Load event to add the Form1_Load event to your code.
  21. Paste the following code in the Form1_Load event:
    //Create an arraylist.
    arrayList = new ArrayList();
    
    arrayList->Add(new Guitar(S"GibSon",S"Les Paul",1958));
    arrayList->Add(new Guitar(S"Fender",S"Jazz Bass",1958));
    arrayList->Add(new Guitar(S"Guild",S"Bluesbird",1958));
    
                
     currencyManager = dynamic_cast <CurrencyManager*>
                     (dataGrid1->BindingContext->Item[arrayList]);
    // Bind the Array List to DataGrid.
    dataGrid1->DataSource = arrayList;
    
  22. Switch to Form Designer.
  23. Double-click Next, and then add the following code to the button1_Click event:
    //Move to the next position.
    currencyManager->Position++;
    
  24. Double-click Previous, and then add the following code to the button2_Click event:
    //Move to the previous position.
    currencyManager->Position--;
    
  25. Double-click First, and then add the following code to the button3_Click event:
    //Move to the first position.
    currencyManager->Position =0;
    
  26. Double-click Last, and then add the following code to the button4_Click event:
    //Move to the last position.
    currencyManager->Position = currencyManager->Count -1;
    
  27. Build, and then run the project.
  28. Click the command buttons to move through the rows of the DataGrid control. Notice that you can edit the values of the objects, if you need to.

REFERENCES

For more information about consumers of data on Windows forms, visit the following Microsoft Developer Web site:
http://msdn2.microsoft.com/en-us/library/aa983578(VS.71).aspx

Properties

Article ID: 816164 - Last Review: May 13, 2007 - Revision: 2.2
APPLIES TO
  • Microsoft Visual C++ 2005 Express Edition
  • Microsoft Visual C++ .NET 2003 Standard Edition
Keywords: 
kbdatabinding kbcollections kbhowtomaster kbhowto KB816164

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