Moving Rows in CListCtrl

This article is very strightfoward but I thought it was a feature that most people could use in their own custom CListCtrls or CListViews.

I had the need in one of my projects to allow the user to rearrange the order of the ListCtrl but I didn't want to allow them to drag and drop. Therefore I came up with this.

 

代码
BOOL CListCtrlEx::MoveRow( int  from,  int  to)
{
    
// Can't move to the same place, or from or to a negative index
     if (from  ==  to  ||  from  <   0   ||  to  <   0 )
        
return  FALSE;

    
// First Copy the row to the new location
     if (CopyRow(from, to))
    {
        
// If we have just inserted a row before
        
// this one in the list, we need to increment
        
// our index.
         if (from  >  to)
            DeleteItem(from 
+   1 );
        
else
            DeleteItem(from);

        
return  TRUE;
    }
    
else
        
return  FALSE;
}

BOOL CListCtrlEx::CopyRow(
int  from,  int  to)
{    
    
// Can't move to the same place, or from or to a negative index
     if (from  ==  to  ||  from  <   0   ||  to  <   0 )
        
return  FALSE;

    
// Copy the row to the new index
    InsertItem(to, GetItemText(from,  0 ));

    
// If row has been inserted before original
    
// increment the original
     if (from  >  to)
        from
++ ;

    
// Loop through subitems
     for ( int  i  =   1 ; i  <  GetColumnCount(); i ++ )
    {
        SetItemText(to, i, GetItemText(from, i));
    }

    
return  TRUE;
}

 

 

Remember that if you want to move a row one row upwards in the list you can use:

m_List.MoveRow(index, index  -   1 );

 

But to move it one row down you need:
m_List.MoveRow(index, index  +   2 );

This is because if you just enter 'index + 1' as the destination, the new row is inserted immeadiately after the current one. The current one is then deleted so you end up in the same place!

Ahh... Trial and Error is a wonderful thing.

转载于:https://www.cnblogs.com/ciey/archive/2010/07/28/1787395.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值