MFC_CListCtrl列的排序

在网上看了许多排序的方法,都没看懂,初学者的悲剧,然后就自己弄了个,请大家指正.
ClistCtrl控件的行带着一个结构体,不过那结构体不好懂,看得眼花缭乱.好多也弄不明白,就自己写了个结构体,把一行的数据全写入结构体中,
交换两结构体的数据就简单多了.
typedef struct
{
wchar_t id[6]; //编号
wchar_t name[10]; //姓名
wchar_t sex[2]; //性别
int age; //年龄
wchar_t fenlei[6]; //分类
wchar_t tel[12]; //电话
}myTongXiLu;

[.cpp]
写两个函数,把结构体写入指定行中,一个从指定行中的数据写入结构体中
//写入
void CMFCApp_CFile_testDlg::SetItemInofToxiluJG(int selIndex,myTongXiLu* toxilu)
{
CString str;
m_list.SetItemText(selIndex, 0, LPCTSTR(toxilu->id));
m_list.SetItemText(selIndex, 1, toxilu->name);
m_list.SetItemText(selIndex, 2, toxilu->sex);
str.Format(_T("%d"), toxilu->age);
m_list.SetItemText(selIndex, 3, str);
m_list.SetItemText(selIndex, 4, toxilu->fenlei);
m_list.SetItemText(selIndex, 5, toxilu->tel);
}
//读取数据
myTongXiLu CMFCApp_CFile_testDlg::GetToxiluJGInofItem(int selIndex)
{
CString str;
myTongXiLu toxilu;
_tcscpy_s(toxilu.id, m_list.GetItemText(selIndex, 0));

_tcscpy_s(toxilu.name, m_list.GetItemText(selIndex, 1));
_tcscpy_s(toxilu.sex, m_list.GetItemText(selIndex, 2));
str = m_list.GetItemText(selIndex, 3);
if (!str.IsEmpty() ||str.SpanIncluding(_T("0123456789"))==str)
	toxilu.age = _ttoi(str);
else
{
	toxilu.age = 0;
}

_tcscpy_s(toxilu.fenlei, m_list.GetItemText(selIndex, 4));
_tcscpy_s(toxilu.tel, m_list.GetItemText(selIndex, 5));
return toxilu;

}

接下来就是数据交换了,有的还要转换数字,我就懒得转换了,全是以字符串来比较,

rowInt:为要比较的总行数,原来没弄这参数,每次都要全部比较,所以后来弄个限制行数,比较了的行就不再比较,依次递减.
ColInt:为要比较的列的索引
bol:为true为升序,为flase为降序,

void CMFCApp_CFile_testDlg::CListCtrlShort(int rowInt,int ColInt, bool bol /= true/)
{
CListCtrl* pList = (CListCtrl)GetDlgItem(IDC_LIST1);
myTongXiLu toxi1, toxi2;
CString str1, str2;
int n = 0;
for (int i = 0; i<rowInt-1; i++)
{
toxi1 = GetToxiluJGInofItem(i);
toxi2 = GetToxiluJGInofItem(i + 1);
str1 = pList->GetItemText(i, ColInt);
str2 = pList->GetItemText(i + 1, ColInt);
n = StrCmpW(str1, str2);
if (bol = true)//判断是升序还是降序,为true为升序
{
if (n>0)
{
/
toxiT = toxi1;
toxi1 = toxi2;
toxi2 = toxiT;*/
SetItemInofToxiluJG(i, &toxi2);
SetItemInofToxiluJG(i + 1, &toxi1);
}
}
else
{
if (n < 0)
{
SetItemInofToxiluJG(i, &toxi2);
SetItemInofToxiluJG(i + 1, &toxi1);
}
}

}

}

//鼠标点击列表头事件
void CMFCApp_CFile_testDlg::OnHdnItemclickList1(NMHDR *pNMHDR, LRESULT *pResult)
{
*pResult = 0;

int colInt;
NMLISTVIEW* pListView = (NMLISTVIEW*)pNMHDR;
if (-1 != pListView->iItem)
{
	colInt = pListView->iItem;//获得鼠标点击的列的索引
	/*CString str;
	str.Format(_T("item: %d, subitem: %d"), pListView->iItem, pListView->iSubItem);
	AfxMessageBox(str);*/
}
//循环比较,最大的放最后,依次递减
for (int j=m_list.GetItemCount();j>=1;j--)
{
	CListCtrlShort(j,colInt,true);
}	

}
大功告成,以后再去学习它自带的结构体.

posted @ 2020-02-25 22:17  初吻给了烟灬  阅读(425)  评论(0编辑  收藏  举报