C++

Programming MSFlexGrid in MFC (VC++)

Representation of data is one the central aspects of any application. Tabular representation of data is the most common method of representing given data. Each language/framework provides its own technique, in the form of controls, to present data in tabular format. MFC (Microsoft Foundation Classes) is no exception. One of the controls that it provides is the MSFlexGrid control.

The application that is going to be developed is based on an example provided by Miss Sormita Chakraborty. The application will take user input and save the input data. The application components will include an SDI window and a dialog that contains the MSFlexGrid. So let's get started.

The first step is to create an SDI-based application. Then we will add a dialog to the application. Since these are common steps, I will not elaborate on them here. After taking these steps, we will add an MSFlexGrid component by using Components and the controls dialog box. Next, we add a variable for representing the grid control. Let's name it m_edit.

Then add the following code in the function for the KeyPressed event:

void CEditGrid::OnKeyPressGrid(short FAR* KeyAscii)

{

ASSERT (KeyAscii != NULL);

m_edit.SetWindowText(GetText());

if (*KeyAscii == 13)

{

m_edit.SetSel(0,-1);

}

else

{

CString str;

str = (CString)*KeyAscii;

m_edit.SetSel(-1,-1);

m_edit.ReplaceSel(str);

}

//Adjust for border height and

//Convert from twips to screen units

m_edit.MoveWindow(((GetCellLeft() - m_lBorderWidth) * m_nLogX)/1440,

((GetCellTop() - m_lBorderHeight) * m_nLogY)/1440,

(GetCellWidth()* m_nLogX)/1440,

(GetCellHeight()* m_nLogY)/1440, FALSE);

m_edit.ShowWindow(SW_SHOW);

m_edit.SetFocus();

}

The code checks to see whether the key pressed has a value of 13. If not, it is saved in a string variable named str. Then it sets the value in the grid. Next, the data retrieved needs to be saved. For that, two arrays are declared in the class that provides the edit functionality for the grid, which is named CEditGrid. The following are the statements:

public:

int m_nLogY;

int m_nLogX;

int i;

int j;

int count;

CString inputx[200][2];

CString inputy[200][2];

virtual ~CEditGrid();

// virtual void GetInput(CString buf);

virtual void CEditGrid::GetTextGrid();

//other parts not shown for brevity

Once that is done, the values are taken from the grid. The following method contains the logic

void CEditGrid::GetTextGrid()

{

CString strx;

CString stry;

long h=CMSFlexGrid::GetCol()-1;

long r=CMSFlexGrid::GetRow()-1;

if(h==0)

{

inputx[r][h]=CMSFlexGrid::GetText();

i++;

}

else

if(h==1)

{

inputy[r][h]=CMSFlexGrid::GetText();

j++;

}

count++;

}

This method is called from the onUpdateGrid method of the EditGrid class.