I know this must be simple, but I can't figure out how to add columns to my datagrid control. I provided it with a data source and I am able to set the two default columns that it gives me to two columns from the data source, but I can't see how to add the rest of the columns. I started out using DBGrid and was able to add columns by right clicking in the control and inserting columns. When I tried this in the datagrid control I only get the properties sheet.
SYMPTOMS
Microsoft DataGrid version 6.0 does not support modifications to the columns of Grid at design time when using it in Visual C++.
RESOLUTION
You can manipulate the columns of DataGrid programmatically at run time. The sample code below shows how to add/remove a column, and modify the column's caption when using ADO data control and DataGrid with an MFC CVCDataGridDlg class.
Insert the following variables and member function prototypes in the corresponding dialog class declaration:
CDataGrid m_Grid; // DataGrid variable.
CAdodc m_DataControl; // ADO Data Control variable.
void OnAdd( ) // Function for adding a column.
void OnRemove( ) // Function for removing a column.
void OnModify( ) // Function for modifying a column.
// Adding a column.
void CVCDataGridDlg::OnAdd()
{
//Get the total number of columns.
short i = (short)(m_DataGrid.GetColumns().GetCount());<BR/>
//Insert the new column.
m_DataGrid.GetColumns().Add(i);
CString rCaption;
GetDlgItemText(IDC_EDIT2,rCaption);
//Set the caption of the column.
m_DataGrid.GetColumns().GetItem(_variant_t(i)).SetCaption((LPCTSTR)rCaption);
m_DataGrid.Refresh();
}
Bookmarks