Gridview中拖动Item互换行数据    

翻译
Rupesh BuradDrag and drop gridview item for changging the order of the items
icscs译 for MSPROJECT.CN

简介
在DragAndDropGridView中,用户可以通过拖拽item重新排序每行数据。用户可以拖动一个Gridview的Item,然后把它放到任何希望放的行互换这两行的次序。


 

 

 

 

 

 

 

 

 

 

代码使用

添加控件到toolbox里,或者添加引用Utility.dll。绑定数据源,添加一个DragAndDropEvent句柄。DragAndDropEventArgs里记录了Start索引和End索引(就是源位置和目标位置)。然后,根据他们属性GridView。

原理
该控件继承与gridview控件。

处理行事件
鼠标按下、鼠标释放的处理如下:

protected override void OnRowDataBound(GridViewRowEventArgs e)
    {
        base.OnRowDataBound(e);
       //set the java script method for the dragging

        e.Row.Attributes.Add("onmousedown", "startDragging" + this.ClientID + "(" + e.Row.RowIndex + ",this); ");
        e.Row.Attributes.Add("onmouseup", "stopDragging" + this.ClientID + "(" + e.Row.RowIndex + "); ");
    }
document.onmousemove = function ()
        {
            if(__item" + this.ClientID + @" != null){
                __item" + this.ClientID + @".style.left=  window.event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft ;
                __item" + this.ClientID + @".style.top =   window.event.clientY + document.body.scrollTop + document.documentElement.scrollTop ;
              }
        }


注册PostBack脚本

我们通过Page.ClientScript.GetPostBackEventReference(this, "")函数在客户端注册__doPostBack方法。

Raise PostBack 事件

 

protected override void RaisePostBackEvent(string eventArgument)
{
    base.RaisePostBackEvent(eventArgument);
    //Handle the post back event

    //and set the values of the source and destination items

    if (Page.Request["__EVENTARGUMENT"] != null && Page.Request["__EVENTARGUMENT"] != "" && Page.Request["__EVENTARGUMENT"].StartsWith("GridDragging"))
    {
        char[] sep = { ',' };
        string[] col = eventArgument.Split(sep);
        DragAndDrop(this, new DragAndDropEventArgs(Convert.ToInt32(col[1]), Convert.ToInt32(col[2])));
    }
}


DragAndDropEventArgs

该事件参数包含下面的索引参数:

public class DragAndDropEventArgs : EventArgs
    {
        private int _startIndex;
        /// 

        /// Index of the source item

        /// 

        public int StartIndex
        {
            get { return _startIndex; }

        }
        private int _endIndex;
        /// 

        /// Index of the destination item

        /// 

        public int EndIndex
        {
            get { return _endIndex; }

        }
        public DragAndDropEventArgs(int startIndex, int endindex)
        {
            _startIndex = startIndex;
            _endIndex = endindex;
        }
    }

关联文档