Can't delete last column in ListView?

I have a bit of a problem here. I can't seem to delete all columns or (reset) the listview. Here's the relevant code:

HWND resultListView = GetDlgItem(hwnd, IDC_RESULTCONTROL);
SendMessage(resultListView, LVM_DELETEALLITEMS, 0, 0); //All items are deleted

//Get numebr of columns
HWND hWndHdr = (HWND)::SendMessage(resultListView, LVM_GETHEADER, 0, 0);
int count = (int)::SendMessage(hWndHdr, HDM_GETITEMCOUNT, 0, 0L);

for (int colIndex = 0; colIndex < count; colIndex++) {
    ListView_DeleteColumn(resultListView, colIndex);
}

///... Irrelevant code

HWND listbox = GetDlgItem(hwnd, IDC_SELECTEDLISTBOX);
int numberOfItemsSelected = SendMessage(listbox, LB_GETLISTBOXINFO, 0, 0);
vector<string> selectedItemsStringsVector;
char buf[250];
LVCOLUMN buffer;

//Add Selected Columns
for (int i = 0; i < numberOfItemsSelected; i++) { //In this case always 2 "Date" and "Time" for testing.
    SendMessage(listbox, LB_GETTEXT, i, (LPARAM)buf);
    selectedItemsStringsVector.push_back(buf);
    buffer.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT;
    buffer.fmt = LVCFMT_LEFT;
    buffer.cx = 100;
    buffer.pszText = buf;
    buffer.cchTextMax = lstrlen(buf);
    buffer.iSubItem = i;
    buffer.iImage = 0;
    buffer.iOrder = 0;
    ListView_InsertColumn(resultListView, i, &buffer); //Works fine. Maybe I add an extra column here?? 
}

      

In debug mode, all my variables have the expected values.

FirstButtonClick

the number of columns in debug mode (variable count = 2) - everything is fine.

image

SecondButtonClick

Column = 3. But it doesn't delete them?

image

English is not my primary language and I am a little frustrated right now ...

+3


source to share


1 answer


Column indices in the control are always numbered sequentially starting from 0. User code does not control the column index. When a column is dropped, the column indices are shifted to higher indices by 1. This is the reason the call ListView_DeleteColumn

ultimately fails.

There are two options for solving this problem:

  • Dropping columns starting at the final index down to 0. Dropping the last column does not change the index of the other columns, so they are stable during the delete operation.
  • Always delete the first column (at index 0).


The second option is easier to implement and also easier to read. The following loop will delete all columns:

for (int colIndex = 0; colIndex < count; ++colIndex) {
    ListView_DeleteColumn(resultListView, 0);
}

      

+4


source







All Articles