c++mfcclistctrl

How to adjust the width of CListCtrl columns to fit the longest string in each column?


I am trying:

void MyListCtrl::UpdateWidthOfColumns( void )
{

  int NofColumns = GetItemCount();
  for (int i = 0; i < NofColumns - 1 ; ++i)
  {
      SetColumnWidth( i, LVSCW_AUTOSIZE_USEHEADER );
  }
}

result: width of each column is adjusted to it`s header string size, not to the largest string.
What I am doing wrong?


Solution

  • You are doing this:

    SetColumnWidth( i, LVSCW_AUTOSIZE_USEHEADER );
    

    According to MSDN

    LVSCW_AUTOSIZE_USEHEADER: Automatically sizes the column to fit the header text.

    You need to go through each column, find the longest string:

    CSize   sz;
    
    for (/*for each column, go through each row*/)
    {
       sz = pDC->GetTextExtent(str); // get string size for each row
       if (sz.cx > dx)
          dx = sz.cx;
    }
    

    Then

    // Set the column width to the largest string.

    SetColumnWidth(dx);