How to bind an array of objects to a Windows Form by using Visual C++ .NET or Visual C++ 2005 (815799)



The information in this article applies to:

  • Microsoft Visual C++ .NET (2003)
  • Microsoft .NET Framework 1.1
  • Microsoft Visual C++ 2005 Express Edition

For a Microsoft Visual Basic .NET version of this article, see 313639.
For a Microsoft Visual C# .NET version of this article, see 313635.
This article refers to the following Microsoft .NET Framework Class Library namespace:
  • System::Collections
  • System::Windows::Forms

IN THIS TASK

SUMMARY

This step-by-step article describes how to bind an array of objects to a Windows form. The example includes a Windows form with three text boxes to display the object properties and includes four command buttons to browse the array.

back to the top

Requirements

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
  • An intermediate understanding of C++ programming concepts
back to the top

Code Description

This section highlights the coding concepts that you must have to do this task.

back to the top

Design the Class

A class that you bind to a control 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 by using 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; 
        }
};
back to the top

Add Class Instances to an Array

To create class instances and add them to the array, follow these steps:
  1. Declare an array.
  2. Create instances of the class, and then add the instances to the array as follows:
    private: Guitar *arr[];
    
    arr = new Guitar *[3];
    arr[0] = new Guitar(S"Gibson", S"Les Paul", 1958);
    arr[1] = new Guitar(S"Fender", S"Jazz Bass", 1964);
    arr[2] = new Guitar(S"Guild", S"Bluesbird", 1971);
back to the top

Bind the Object Properties to Form Controls

After you populate the array, you can bind the individual properties of the object to Windows Forms controls. To do this, follow these steps:
  1. Call the Add method of the Textbox DataBindings property.
  2. Pass the control property to bind the name of the array, and the property of the object as follows:
    textBox1->DataBindings->Add(S"Text", arr, S"make");
    textBox2->DataBindings->Add(S"Text", arr, S"model");
    textBox3->DataBindings->Add(S"Text", arr, S"year");
back to the top

Browse the Array

You can use a CurrencyManager class to move through the array. To do this, associate the CurrencyManager class with the BindingContext function of the form (in this case, the array).
private: CurrencyManager *currencyManager;
currencyManager = NULL;
currencyManager = static_cast<CurrencyManager*>(this->BindingContext->get_Item(arr) );
The CurrencyManager class has a Position property that you can change to iterate over the members of the array. By adding to or subtracting from the current value of the Position property, you can display different members of the array on the form.
//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 = arr->Length - 1;
back to the top

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 Q815799, 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 Q815799, 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++ Class 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);
    };
    
    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 this code sample. To do this, follow these steps:
    1. Click Project, and then click ProjectName Properties.

      Note ProjectName represents 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 on the right pane, click Apply, and then click OK.
    For more information about the common language runtime support compiler options, 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 three text box controls to Form1, and then arrange the controls horizontally.
  12. Add four button controls to Form1, and then arrange the controls horizontally.
  13. Change the Text property of Button1 control to Next.
  14. Change the Text property of Button2 control to Previous.
  15. Change the Text property of Button3 control to First.
  16. Change the Text property of Button4 control to Last.
  17. Open the Form1.h file, and then add the following code at the beginning:
    #include "Guitar.h"
  18. Add the following code inside the Form1 class:
    private: Guitar *arr[];
    CurrencyManager *currencyManager;
  19. Switch to Form Designer, right-click the form, 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. Add the following code to the Form1_Load event:
    currencyManager	= NULL;
    arr	= new Guitar *[3];
    arr[0] = new Guitar(S"Gibson", S"Les Paul", 1958);
    arr[1] = new Guitar(S"Fender", S"Jazz Bass", 1964);
    arr[2] = new Guitar(S"Guild", S"Bluesbird", 1971);
    currencyManager	= static_cast<CurrencyManager*>(this->BindingContext->get_Item(arr)	);
    
    textBox1->DataBindings->Add(S"Text", arr, S"make");
    textBox2->DataBindings->Add(S"Text", arr, S"model");
    textBox3->DataBindings->Add(S"Text", arr, S"year");
  22. Switch to Form Designer.
  23. Double-click Next, and then add the following code to the button1_Click event:
    currencyManager->Position++;
  24. Double-click Previous, and then add the following code to the button2_Click event:
    currencyManager->Position--;
  25. Double-click First, and then add the following code to the button3_Click event:
    currencyManager->Position = 0;
  26. Double-click Last, and then add the following code to the button4_Click event:
    currencyManager->Position = arr->Length - 1;
  27. Build, and then run the project.
  28. Click the command buttons to display different array elements. Notice that you can edit the values of the objects if you must.
back to the top

Use a Structure Instead of a Class

The rules for binding a structure are the same as the rules for binding an object. You must have property (member) accessors. Create a structure that resembles a class for this purpose. To bind to an array of structures, follow these steps:
  1. Change the definition of the Guitar class from the following:
    __gc class Guitar
    to the following:
    __gc struct Guitar
  2. Build and run the sample program again. Verify that it functions with an array of structures.
back to the top

REFERENCES

For more information about consumers of data on Windows Forms, visit the following Microsoft Developer Network Web site:back to the top

Modification Type:MajorLast Reviewed:1/17/2006
Keywords:kbDataBinding kbCollections kbControl kbHOWTOmaster KB815799 kbAudDeveloper