當前位置:首頁 > IT技術(shù) > 編程語言 > 正文

CListCtrl,按照某列進行排序(本地數(shù)據(jù)倒序、正序)---SetItemData和GetItemData
2022-04-18 11:04:09

1、h文件中

afx_msg void OnColumnClick(NMHDR *pNMHDR, LRESULT *pResult);

int static CALLBACK CompareByTime(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort);

CListCtrl m_list_;

  

記得是CListCtrl類。如果用子類,記得看一下是否有OnColumnClick

?

2、cpp文件中:

BEGIN_MESSAGE_MAP(CDlgOssJson, CBCGPDialog)
	ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST_ITEMS, &CDlgOssJson::OnLvnItemchangedList)
	ON_NOTIFY(LVN_COLUMNCLICK, IDC_LIST_ITEMS, &CDlgOssJson::OnColumnClick)
END_MESSAGE_MAP()

  

BOOL CDlgOssJson::OnInitDialog()
{
	CBCGPDialog::OnInitDialog();

	DWORD dwStyle = m_list_.GetExtendedStyle();
	dwStyle |= LVS_EX_FULLROWSELECT;
	dwStyle |= LVS_EX_GRIDLINES;
	dwStyle |= LVS_EX_CHECKBOXES;
	m_list_.SetExtendedStyle(dwStyle);	
	int nCol = 0;    //列標題
	m_list_.InsertColumn(nCol++, _T("名稱"), LVCFMT_CENTER, 300);
	m_list_.InsertColumn(nCol++, _T("上傳時間"), LVCFMT_CENTER, 200);

	GetItemsData(1);
	return TRUE;
}

void CDlgOssJson::OnLvnItemchangedList(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
	if (pNMLV->iSubItem == 0)
	{
		BOOL bChk = TRUE;
		int nCount = m_list_.GetItemCount();
		for(int i = 0; i < nCount; ++i)
		{
			bChk = m_list_.GetCheck(i);
			if (!bChk)
			{
				break;
			}
		}
		m_chk_all_.SetCheck(bChk);
	}
	*pResult = 0;
}

int CALLBACK CDlgOssJson::CompareByTime(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
	oss_json_data *cd1 = (oss_json_data*)(LPARAM)lParam1;    //SetItemData時的值
	oss_json_data *cd2 = (oss_json_data*)(LPARAM)lParam2;
	if (cd1 != NULL && cd2 != NULL)
	{
		return st_bMethod ? cd1->strTime.CompareNoCase(cd2->strTime) : cd2->strTime.CompareNoCase(cd1->strTime);
	}
	else
	{
		return int(st_bMethod);
	}
}

void CDlgOssJson::OnColumnClick(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
	*pResult = 0;

	if (st_nSortColumn == pNMLV->iSubItem)
	{
		st_bMethod = !st_bMethod;
		m_list_.SortItems(CompareByTime, (DWORD_PTR)&m_list_);    //(DWORD_PTR)this也可以將this對話框傳入CompareByTime
	}
}

  
重點來了
要記得

	m_list_.DeleteAllItems();
	int iSize = m_vec_items_.size();
	for (int i = 0; i < iSize; ++i)
	{
		CString strItem = _T("");
		strItem.Format(_T("%d"), i + 1);
		m_list_.InsertItem(i, strItem);    //行標題
		m_list_.SetItemData(i, (LPARAM)(oss_json_data*)&m_vec_items_[i]);    //列排序時用
		m_list_.SetItemText(i, 0, m_vec_items_[i].strProjName);
		m_list_.SetItemText(i, 1, m_vec_items_[i].strTime);
	}

  

本文摘自 :https://www.cnblogs.com/

開通會員,享受整站包年服務(wù)立即開通 >