Inserting and Deleting a row or column of cells

Many of the cell operations implemented by TCustomGrid, from which TStringGrid descends, are protected.  Fortunately, the TStrings class, of which the StringGrid's Rows and Cols property are an instance of, offers useful functions for handling an array of strings.  Below, I demonstrate, using two sample functions, how to insert and delete StringGrid columns.  A similar approach can be used for the rows.

KEYWORDS: ColCount, RowCount
 

 

//-----------------------------------------------------------------------------
//in source...

//Insert a column
void __fastcall TForm1::InsertCol(TStringGrid *StringGrid, long AfterIndex)
{
    StringGrid->ColCount = StringGrid->ColCount + 1;
    for (int col = StringGrid->ColCount - 1; col > AfterIndex + 1; col--)
    {
        StringGrid->Cols[col] = StringGrid->Cols[col - 1];
    }
    StringGrid->Cols[AfterIndex + 1]->Clear();
}

//-----------------------------------------------------------------------------

//Remove a column
void __fastcall TForm1::RemoveCol(TStringGrid *StringGrid, long Index)
{
    for (int col = Index; col < StringGrid->ColCount - 1; col++)
    {
        StringGrid->Cols[col] = StringGrid->Cols[col + 1];
    }
    StringGrid->ColCount = StringGrid->ColCount - 1;
}