CListCtrl实现按列排序

在CInstallbaseDlg.h中在类定义之前添加如下代码:(定义一个结构体和一个全局变量)

[cpp]  view plain copy
  1. struct DATA  
  2. {  
  3.     CListCtrl *plist;//用于存储列表控件的指针  
  4.     int col;//用于存储要排序主列的序号  
  5. };//回调函数第三个参数对应的数据结构,可以自定义,至少要包含这两项  
  6. BOOL fav=FALSE;//排序方法(递增或递减)  
在CInstallbaseDlg.cpp中定义回调函数MylistCompare:

[cpp]  view plain copy
  1. int CALLBACK MylistCompare(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)  
  2. {  
  3.     DATA * MyData=(DATA*)lParamSort;  
  4.     int col=MyData->col;//点击的列项传递给col,用来判断点击了第几列  
  5.     //取项的字符串  
  6.     CString strItem1, strItem2;  
  7.     strItem1=MyData->plist->GetItemText(lParam1,col);  
  8.     strItem2=MyData->plist->GetItemText(lParam2,col);//获得要比较的字符串                                                                                     //因我的列表框有16列,且第16列为日期列,故做了如下的操作,如果只是字符串的话,只执行if下面的语句应该就好了,其实我觉得日期比较也可用if下面的语句达       //到效果,只是已经写上去了,就懒得再做修改                                                                                                                 if(col!=15)//说明比较的不是日期列  
[cpp]  view plain copy
  1.     return strItem1.CompareNoCase(strItem2);//不区分大小写进行比较  
  2. else  
  3. {  
  4.       
  5.     int year1=atoi(strItem1.Left(4));  
  6.     int year2=atoi(strItem2.Left(4));  
  7.     if(year1==year2)  
  8.     {  
  9.         int mon1=atoi(strItem1.Left(7).Right(2));  
  10.         int mon2=atoi(strItem2.Left(7).Right(2));  
  11.         if(mon1==mon2)  
  12.         {  
  13.             int day1=atoi(strItem1.Right(2));  
  14.             int day2=atoi(strItem2.Right(2));  
  15.             return day1-day2;  
  16.         }  
  17.         else  
  18.             return mon1-mon2;  
  19.     }  
  20.     else   
  21.         return year1-year2;  
  22. }  
对对话框中的listctrl控件添加消息LVN_COLOUMCLICK_响应函数:

[cpp]  view plain copy
  1. void CInstallbaseDlg::OnColumnclickList(NMHDR* pNMHDR, LRESULT* pResult)   
  2. {  
  3.     NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;  
  4.     // TODO: Add your control notification handler code here  
  5.   
  6.     DATA data;  
  7.     data.col=pNMListView->iSubItem;//取列  
  8.     data.plist=&m_list;//取列表指针  
  9.     fav=!fav;//排序每点一次列就变一次,若想固定排序,那就去掉这局  
  10.     //设置列表相关项,以便排序  
  11.     int len=m_list.GetItemCount();  
  12.     for(int i=0;i<len;i++)  
  13.     {  
  14.         m_list.SetItemData(i,i);  
  15.     }  
  16.   
  17.     m_list.SortItems(MylistCompare,(LPARAM)&data);  
  18.   
  19.     *pResult = 0;  
  20. }  

我对回调函数不了解,对 SortItems也不了解,只是个人觉得 CListCtrl成员函数 SortItems的两个参数第一个是回调函数的名称,第二个参数和回调函数中第三个参数是同一个值

你可能感兴趣的:(数据结构,ListView,存储)