첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
유용한 소스 코드가 있으면 icodebroker@naver.com으로 보내주시면 감사합니다.
블로그 자료는 자유롭게 사용하세요.

■ DataGridView 클래스 : 마우스를 사용해 항목 순서 변경하기

------------------------------------------------------------------------------------------------------------------------


TestProject.zip


MainForm.cs

 

 

using System;

using System.Collections;

using System.Collections.Generic;

using System.Drawing;

using System.Windows.Forms;

 

namespace TestProject

{

    /// <summary>

    /// 메인 폼

    /// </summary>

    public partial class MainForm : Form

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field

        ////////////////////////////////////////////////////////////////////////////////////////// Private

 

        #region Field

 

        /// <summary>

        /// 마우스 DOWN 행 인덱스

        /// </summary>

        private int mouseDownRowIndex;

 

        /// <summary>

        /// 마우스 DOWN 사각형

        /// </summary>

        private Rectangle mouseDownRectangle;

 

        /// <summary>

        /// 드레그 DROP 행 인덱스

        /// </summary>

        private int dragDropRowIndex;

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - MainForm()

 

        /// <summary>

        /// 생성자

        /// </summary>

        public MainForm()

        {

            InitializeComponent();

 

            #region 리스트를 설정한다.

 

            List<DataItem> list = new List<DataItem>();

 

            list.Add(new DataItem { Item = "형식"          , Description = "쌍발 복좌 고등 훈련기"                                     });

            list.Add(new DataItem { Item = "전폭"          , Description = "7.70m"                                                     });

            list.Add(new DataItem { Item = "전장"          , Description = "14.14m"                                                    });

            list.Add(new DataItem { Item = "전고"          , Description = "3.92m"                                                     });

            list.Add(new DataItem { Item = "주익 면적"     , Description = "15.8m²"                                                   });

            list.Add(new DataItem { Item = "최대 이륙 중량", Description = "5,466kg"                                                   });

            list.Add(new DataItem { Item = "엔진"          , Description = "GE J85-GE-5R 터보 제트 엔진 (Dry 995kg, A/B 1,497kg) × 2" });

            list.Add(new DataItem { Item = "최대 속도"     , Description = "M 1.23/10,973m"                                            });

            list.Add(new DataItem { Item = "순항 속도"     , Description = "M 0.95/10,973m"                                            });

            list.Add(new DataItem { Item = "상승 한도"     , Description = "16,335m"                                                   });

            list.Add(new DataItem { Item = "항속 거리"     , Description = "1,768km(최대 연료)"                                        });

            list.Add(new DataItem { Item = "이륙활주거리"  , Description = "762m"                                                      });

            list.Add(new DataItem { Item = "착륙활주거리"  , Description = "915m"                                                      });

            list.Add(new DataItem { Item = "승무원"        , Description = "2명"                                                       });

            list.Add(new DataItem { Item = "가격"          , Description = "756,000달러(1961년)"                                       });

 

            #endregion

            #region 데이터 그리드 뷰를 설정한다.

 

            this.dataGridView.AllowDrop = true;

 

            #endregion

 

            SetDataGridViewData(list);

 

            #region 이벤트를 설정한다.

 

            this.dataGridView.MouseDown += dataGridView_MouseDown;

            this.dataGridView.MouseMove += dataGridView_MouseMove;

            this.dataGridView.DragOver  += dataGridView_DragOver;

            this.dataGridView.DragDrop  += dataGridView_DragDrop;

 

            #endregion

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Private

        //////////////////////////////////////////////////////////////////////////////// Event

 

        #region 데이터 그리드 뷰 마우스 DOWN 처리하기 - dataGridView_MouseDown(sender, e)

 

        /// <summary>

        /// 데이터 그리드 뷰 마우스 DOWN 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void dataGridView_MouseDown(object sender, MouseEventArgs e)

        {

            DataGridView dataGridView = sender as DataGridView;

 

            this.mouseDownRowIndex = dataGridView.HitTest(e.X, e.Y).RowIndex;

 

            if(this.mouseDownRowIndex != -1)

            {

                Size dragSize = SystemInformation.DragSize;

 

                this.mouseDownRectangle = new Rectangle(new Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)), dragSize);

            }

            else

            {

                this.mouseDownRectangle = Rectangle.Empty;

            }

        }

 

        #endregion

        #region 데이터 그리드 뷰 마우스 이동시 처리하기 - dataGridView_MouseMove(sender, e)

 

        /// <summary>

        /// 데이터 그리드 뷰 마우스 이동시 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void dataGridView_MouseMove(object sender, MouseEventArgs e)

        {

            DataGridView dataGridView = sender as DataGridView;

 

            if((e.Button & MouseButtons.Left) == MouseButtons.Left)

            {

                if(this.mouseDownRectangle != Rectangle.Empty && !this.mouseDownRectangle.Contains(e.X, e.Y))

                {

                    dataGridView.DoDragDrop(dataGridView.Rows[mouseDownRowIndex], DragDropEffects.Move);

                }

            }

        }

 

        #endregion

        #region 데이터 그리드 뷰 드래그 OVER 처리하기 - dataGridView_DragOver(sender, e)

 

        /// <summary>

        /// 데이터 그리드 뷰 드래그 OVER 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void dataGridView_DragOver(object sender, DragEventArgs e)

        {

            e.Effect = DragDropEffects.Move;

        }

 

        #endregion

        #region 데이터 그리드 뷰 드래그 DROP 처리하기 - dataGridView_DragDrop(sender, e)

 

        /// <summary>

        /// 데이터 그리드 뷰 드래그 DROP 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void dataGridView_DragDrop(object sender, DragEventArgs e)

        {

            if(e.Effect != DragDropEffects.Move)

            {

                return;

            }

 

            DataGridView dataGridView = sender as DataGridView;

 

            if(dataGridView.DataSource == null) // 데이터 소스를 설정한 경우만 처리 대상으로 한정했다.

            {

                return;

            }

 

            Point dropPoint = dataGridView.PointToClient(new Point(e.X, e.Y));

 

            this.dragDropRowIndex = dataGridView.HitTest(dropPoint.X, dropPoint.Y).RowIndex;

 

            DataGridViewRow moveRow = e.Data.GetData(typeof(DataGridViewRow)) as DataGridViewRow;

 

            object sourceItem = moveRow.DataBoundItem;

            object targetItem = dataGridView.Rows[this.dragDropRowIndex].DataBoundItem;

 

            IList sourceList = dataGridView.DataSource as IList;

 

            sourceList.Remove(sourceItem);

 

            int targetIndex = sourceList.IndexOf(targetItem);

 

            sourceList.Insert(targetIndex, sourceItem);

 

            dataGridView.Refresh();

 

            dataGridView.ClearSelection();

 

            dataGridView.Rows[targetIndex].Selected = true;

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////// Functioon

 

        #region 데이터 그리드 뷰 셀 스타일 구하기 - GetDataGridViewCellStyle(backgroundColor, alignment)

 

        /// <summary>

        /// 데이터 그리드 뷰 셀 스타일 구하기

        /// </summary>

        /// <param name="backgroundColor">배경색</param>

        /// <param name="alignment">정렬</param>

        /// <returns>데이터 그리드 뷰 셀 스타일</returns>

        private DataGridViewCellStyle GetDataGridViewCellStyle(Color backgroundColor, DataGridViewContentAlignment alignment)

        {

            DataGridViewCellStyle style = new DataGridViewCellStyle();

 

            style.Alignment = alignment;

            style.BackColor = backgroundColor;

 

            return style;

        }

 

        #endregion

        #region 데이터 그리드 뷰 데이터 설정하기 - SetDataGridViewData(dataSource)

 

        /// <summary>

        /// 데이터 그리드 뷰 데이터 설정하기

        /// </summary>

        /// <param name="dataSource">데이터 소스</param>

        private void SetDataGridViewData(object dataSource)

        {

            if(this.dataGridView.DataSource != null)

            {

                IDisposable disposable = this.dataGridView.DataSource as IDisposable;

 

                this.dataGridView.DataSource = null;

 

                if(disposable != null)

                {

                    disposable.Dispose();

 

                    disposable = null;

                }

            }

 

            #region 리스트 데이터 그리드 뷰 컬럼을 설정한다.

 

            this.dataGridView.Columns.Clear();

 

            DataGridViewColumn column;

 

            column = new DataGridViewTextBoxColumn();

 

            column.Width                      = 150;

            column.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;

            column.HeaderText                 = "항목";

            column.SortMode                   = DataGridViewColumnSortMode.NotSortable;

            column.DataPropertyName           = "Item";

            column.ValueType                  = typeof(string);

            column.DefaultCellStyle           = GetDataGridViewCellStyle(Color.White, DataGridViewContentAlignment.MiddleLeft);

 

            this.dataGridView.Columns.Add(column);

 

            column = new DataGridViewTextBoxColumn();

 

            column.Width                      = 500;

            column.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;

            column.HeaderText                 = "설명";

            column.SortMode                   = DataGridViewColumnSortMode.NotSortable;

            column.DataPropertyName           = "Description";

            column.ValueType                  = typeof(string);

            column.DefaultCellStyle           = GetDataGridViewCellStyle(Color.White, DataGridViewContentAlignment.MiddleLeft);

 

            this.dataGridView.Columns.Add(column);

 

            #endregion

 

            this.dataGridView.DataSource = dataSource;

        }

 

        #endregion

    }

}

 

------------------------------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker

댓글을 달아 주세요