Reputation: 1411
Currently I am working on a listcontrol,where the first column header should consists of a checkbox.Adding checkbox to the list items can be done by setting the style to LVS_EX_CHECKBOXES.Is there any way to add checkbox to the header so that if I check it all the items in the list should get checked and if I uncheck it all the list items should get unchecked.
Can anyone please let me know any possible way of doing so.
Upvotes: 1
Views: 5595
Reputation: 57
The accepted answer was very helpful, but using LVCOLUMN
did not worked well for me.
so I found out using HDITEM
working better for me:
CHeaderCtrl* pHeaderControl = m_ListControl.GetHeaderCtrl();
HDITEM hdi = { 0 };
hdi.mask = HDI_FORMAT;
pHeaderControl->GetItem(0, &hdi);
hdi.fmt |= HDF_CHECKBOX;
if (bAllChecked)
{
hdi.fmt |= HDF_CHECKED;
}
else
{
hdi.fmt &= ~HDF_CHECKED;
}
pHeaderControl->SetItem(0, &hdi);
Upvotes: 0
Reputation: 1411
Follow the below steps to get the checkbox on the header and using that checkbox on the header we can check and uncheck all the items in the list.
In the OnInitDialog() Add this below piece of code:
BOOL OnInitDialog()
{
LVCOLUMN pColumn = {0};
pColumn.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
m_listCtrl.GetColumn(0, &pColumn);
pColumn.fmt |= HDF_CHECKBOX;
pColumn.pszText = L"";
pColumn.cx = 25;
pColumn.iSubItem = 1;
m_listCtrl.InsertColumn(1, &pColumn);//m_listctrl is listcontrol member variable
}
Add this event HDN_ITEMSTATEICONCLICK
void CMFPSearchListView::OnHdnItemStateIconClickListctrl(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMHEADER pNMHeader = (LPNMHEADER)pNMHDR;
// first determine whether the click was a checkbox change
if (pNMHeader->pitem->mask & HDI_FORMAT && pNMHeader->pitem->fmt & HDF_CHECKBOX)
{
// now determine whether it was checked or unchecked
BOOL bUnChecked = pNMHeader->pitem->fmt & HDF_CHECKED;
// apply check state to each list item
for (int nItem = 0; nItem < m_listCtrl.GetItemCount(); nItem++)
m_listCtrl.SetCheck(nItem, !bUnChecked);
}
*pResult = 1; //if pResult = 0 then you will get blue color selection on the items when you check header checkbox , in order to avoid that I made pResult = 1; Now we won't face the selection issue.
}
//Add LVN_ITEMCHANGED
void OnListViewItemchanged(NMHDR *pNMHDR, LRESULT *pResult)
{
LVCOLUMN pColumn = {0};
pColumn.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
m_listCtrl.GetColumn(0, &pColumn);
if(blAllChecked)
pColumn.fmt |= HDF_CHECKED;
else
pColumn.fmt &= ~HDF_CHECKED;
//m_listCtrl.InsertColumn(1, &pColumn);
m_listCtrl.SetColumn(0, &pColumn);
*pResult=0;
}
Note:This header checkbox will work from above Windows XP Operating system.
Upvotes: 1