spin_eight spin_eight - 1 year ago 131
C++ Question

How to iterate through elements of CListCtrl?

Brief description:

I got an instance of

class where objects are stored, when an object is selected corresponding list report for that object is displayed.

I need to adjust width of columns of an instance of the class MyListCtrl which derives from
so that data in that columns can be seen by user without resizing of columns.

How I approach my task:

I implement method InitColumnWidth which is called when object is selected from the tree

void COwnListCtrl::InitColumnWidth ( unsigned const * defwidth, BOOL chars )
/* find the largest string in each column and set column width accordingly
so that user no longer need to manually adjust columns width */

GetClientRect ( & r );
int* arrOfMaxColumnWidth = new int[NumCol]; // array where max length for columns will be stored
for (int i = 0; i < NumCol; ++i)
arrOfMaxColumnWidth[i] = 0; // initialize
tstring dataInColumn;
double Scale = ( defwidth && chars ) ? GetCharAveWidth ( * GetFont () ) : ( r.right * 0.01 );
int numberOfVisitedItems = 0;
dataInColumn = _T(""); // initialize
for (int col = 0; col < NumCol; ++col)
//DWORD const itemData = this->GetItemData(numberOfVisitedItems);

dataInColumn = this->GetSubItemString(this->GetItemData(numberOfVisitedItems), col);
/* 1-st varaint returns only first row of the list
because GetItemData always returns zero, but I need to visit all rows */
dataInColumn = this->GetSubItemString(numberOfVisitedItems, col);
/* 2-nd variant, works for most objects from CTreeCtrl, but for a few of them assertion is raised, system reports on the corrupted heap and application terminates*/
if (dataInColumn.length() > arrOfMaxColumnWidth[col])
arrOfMaxColumnWidth[col] = dataInColumn.length();
while(dataInColumn.length() != 0); /* do{} while loop is used to get number of rows in the table
as long as an empty string is read, which means that all rows were read*/
for (int col = 0; col < NumCol; ++col)
int tmp = ColWidth[col] = arrOfMaxColumnWidth[col] * Scale;
ColWidth[0] = 100;

Need help!

cha cha
Answer Source

use this (replace your for (int col = 0; col < NumCol; ++col) with the code below):

for (int col = 0; col < NumCol; ++col)
    int len = 0;
    for(int row = 0; this->GetItemCount(); ++row)
        CString item = this->GetItemText(row, col);
        if(item.GetLength() > len) len = item.GetLength();
    if (len > arrOfMaxColumnWidth[col])
        arrOfMaxColumnWidth[col] = len; // should you multiple it to Scale?
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download