How to adjust DBGrid columns width automatically

2019-06-11 10:28发布

问题:

I've been try to use this Delphi code with C++ Builder XE. I manually convert the language into C++ Builder language.

This procedure was working correctly. When I try to maximize the form holding the DBGrid, this procedure successfully split the columns width according to the grid width. However, if I try to minimize the form width using mouse control at the right or left of form, this procedure weren't adjust the column width to the length of the values or length of the labels on each columns.

Is there any way to fix it? Or anyone have another procedure to solve problem like this?

EDIT: Ok, here is the code. I've been manually convert the code above into this code:

void __fastcall TfmMain::FixGridColumnsWidth(TDBGrid *DBGrid)
{
int       TotalColumnWidth, ColumnCount, GridClientWidth, Filler, i;


    ColumnCount = DBGrid->Columns->Count;

    if  (ColumnCount == 0)
        exit;

    // compute total width used by grid columns and vertical lines if any
    TotalColumnWidth = 0;

    for ( i = 0; i <=ColumnCount-1; i++)

        TotalColumnWidth = TotalColumnWidth + DBGrid->Columns->Items[i]->Width;
        if ( DBGrid->Options.Contains(dgColLines) )

        // include vertical lines in total (one per column)
            TotalColumnWidth = TotalColumnWidth + ColumnCount;

    // compute grid client width by excluding vertical scroll bar, grid indicator,
    // and grid border
    GridClientWidth = DBGrid->Width - GetSystemMetrics(SM_CXVSCROLL);

    if ( DBGrid->Options.Contains(dgIndicator) )  {
        GridClientWidth = GridClientWidth - IndicatorWidth;
        if ( DBGrid->Options.Contains(dgColLines) )
            GridClientWidth--;
    }

    if ( DBGrid->BorderStyle == bsSingle )  {
        if ( DBGrid->Ctl3D ) {                      // border is sunken (vertical border is 2 pixels wide)
            GridClientWidth = GridClientWidth - 4;
        }
        else {                              // border is one-dimensional (vertical border is one pixel wide)
            GridClientWidth = GridClientWidth - 2;
        }
    }

    // adjust column widths
    if ( TotalColumnWidth < GridClientWidth )  {
        Filler =  (GridClientWidth - TotalColumnWidth) / ColumnCount;
        for ( i = 0; i <= ColumnCount-1; i++ )
            DBGrid->Columns->Items[i]->Width = DBGrid->Columns->Items[i]->Width + Filler;
    }

    else
        if ( TotalColumnWidth > GridClientWidth ) {
            Filler = (TotalColumnWidth - GridClientWidth) / ColumnCount;
            if ( (TotalColumnWidth - GridClientWidth) % ColumnCount != 0 )
                Filler++;
            for ( i = 0; i <= ColumnCount-1; i++ )
                DBGrid->Columns->Items[i]->Width = DBGrid->Columns->Items[i]->Width - Filler;
        }


}

Thanks in advance.