첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
본 블로그는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 블로그 콘텐츠 향상을 위해 쓰여집니다.

728x90
반응형
728x170

TestProject.zip
다운로드

▶ PasteCSVForm.cs

using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace TestProject
{
    /// <summary>
    /// CSV 붙여넣기 폼
    /// </summary>
    public partial class PasteCSVForm : Form
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Delegate
        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region 단순 대리자 - SimpleDelegate()

        /// <summary>
        /// 단순 대리자
        /// </summary>
        private delegate void SimpleDelegate();

        #endregion
        #region 진행 패널 리셋하기 대리자 - ResetProgressPanelDelegate(minimum, maximum)

        /// <summary>
        /// 진행 패널 리셋하기 대리자
        /// </summary>
        /// <param name="minimum">최소값</param>
        /// <param name="maximum">최대값</param>
        private delegate void ResetProgressPanelDelegate(int minimum, int maximum);

        #endregion
        #region 진행 패널 설정하기 대리자 - SetProgressPanelDelegate(message, progressValue)

        /// <summary>
        /// 진행 패널 설정하기 대리자
        /// </summary>
        /// <param name="message">메시지</param>
        /// <param name="value">값</param>
        private delegate void SetProgressPanelDelegate(string message, int value);

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field
        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region Field

        /// <summary>
        /// 헤더 텍스트 사용 여부
        /// </summary>
        private bool useHeaderText = false;

        /// <summary>
        /// 실제 헤더 텍스트 사용 여부
        /// </summary>
        private bool actualUseHeaderText = false;

        /// <summary>
        /// 최대 컬럼 카운트
        /// </summary>
        private int maximumColumnCount = -1;

        /// <summary>
        /// 실제 컬럼 카운트
        /// </summary>
        private int actualColumnCount = -1;

        /// <summary>
        /// 소스 데이터 객체
        /// </summary>
        private IDataObject sourceDataObject = null;

        /// <summary>
        /// 소스 텍스트
        /// </summary>
        private string sourceText = null;

        /// <summary>
        /// 소스 테이블
        /// </summary>
        private DataTable sourceTable = null;

        /// <summary>
        /// 소스 리더
        /// </summary>
        private IDataReader sourceReader = null;

        /// <summary>
        /// 자동 컬럼 크기 허용 여부
        /// </summary>
        private bool allowAutoColumnSizing = false;

        /// <summary>
        /// 자동 행 크기 허용 여부
        /// </summary>
        private bool allowAutoRowSizing = false;

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Property
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 헤더 텍스트 사용 여부 - UseHeaderText

        /// <summary>
        /// 헤더 텍스트 사용 여부
        /// </summary>
        public bool UseHeaderText
        {
            get
            {
                return this.useHeaderText;
            }
            set
            {
                this.useHeaderText = value;
            }
        }

        #endregion
        #region 최대 컬럼 카운트 - MaximumColumnCount

        /// <summary>
        /// 최대 컬럼 카운트
        /// </summary>
        public int MaximumColumnCount
        {
            get
            {
                return this.maximumColumnCount;
            }
            set
            {
                this.maximumColumnCount = value;
            }
        }

        #endregion
        #region 자동 컬럼 크기 허용 여부 - AllowAutoColumnSizing

        /// <summary>
        /// 자동 컬럼 크기 허용 여부
        /// </summary>
        public bool AllowAutoColumnSizing
        {
            get
            {
                return this.allowAutoColumnSizing;
            }
            set
            {
                this.allowAutoColumnSizing = value;
            }
        }

        #endregion
        #region 자동 행 크기 허용 여부 - AllowAutoRowSizing

        /// <summary>
        /// 자동 행 크기 허용 여부
        /// </summary>
        public bool AllowAutoRowSizing
        {
            get
            {
                return this.allowAutoRowSizing;
            }
            set
            {
                this.allowAutoRowSizing = value;
            }
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - PasteCSVForm()

        /// <summary>
        /// 생성자
        /// </summary>
        public PasteCSVForm()
        {
            InitializeComponent();

            this.dataGridView.ReadOnly                 = true;
            this.dataGridView.RowHeadersVisible        = false;
            this.dataGridView.AllowUserToAddRows       = false;
            this.dataGridView.AllowUserToDeleteRows    = false;
            this.dataGridView.AllowUserToOrderColumns  = false;
            this.dataGridView.AllowUserToResizeColumns = true;
            this.dataGridView.AllowUserToResizeRows    = true;
            this.dataGridView.SelectionMode            = DataGridViewSelectionMode.FullRowSelect;
            this.dataGridView.MultiSelect              = true;

            SetDoubleBuffered(this.dataGridView, true);

            GotFocus                                 += Form_GotFocus;
            this.dataGridView.KeyDown                += dataGridView_KeyDown;
            this.okButton.Click                      += okButton_Click;
            this.cancelButton.Click                  += cancelButton_Click;
            this.backgroundWorker.DoWork             += backgroundWorker_DoWork;
            this.backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;

            this.deleteSelectedRowsMenuItem.Click += deleteSelectedRowsMenuItem_Click;
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 데이터 테이블 구하기 - GetDataTable()

        /// <summary>
        /// 데이터 테이블 구하기
        /// </summary>
        /// <returns>데이터 테이블</returns>
        public DataTable GetDataTable()
        {
            return this.sourceTable;
        }

        #endregion
        #region 데이터 리더 구하기 - GetDataReader()

        /// <summary>
        /// 데이터 리더 구하기
        /// </summary>
        /// <returns>데이터 리더</returns>
        public IDataReader GetDataReader()
        {
            if(this.sourceTable == null || this.sourceTable.Rows.Count == 0)
            {
                return null;
            }

            if(this.sourceReader == null)
            {
                this.sourceReader = new DataTableReader(this.sourceTable);
            }

            return this.sourceReader;
        }

        #endregion

        ////////////////////////////////////////////////////////////////////////////////////////// Private
        //////////////////////////////////////////////////////////////////////////////// Event

        #region 폼 포커스 획득시 처리하기 - Form_GotFocus(sender, e)

        /// <summary>
        /// 폼 포커스 획득시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void Form_GotFocus(object sender, EventArgs e)
        {
            this.dataGridView.Focus();
        }

        #endregion
        #region 데이터 그리드 뷰 키 DOWN 처리하기 - dataGridView_KeyDown(sender, e)

        /// <summary>
        /// 데이터 그리드 뷰 키 DOWN 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void dataGridView_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
            {
                if(Clipboard.ContainsData(DataFormats.CommaSeparatedValue))
                {
                    ClearData();

                    this.sourceDataObject = Clipboard.GetDataObject();

                    SetData();
                }
            }
            else if(e.KeyCode == Keys.Delete)
            {
                ProcessDeleteSelectedRows();
            }
        }

        #endregion
        #region 백그라운드 작업자 작업시 처리하기 - backgroundWorker_DoWork(sender, e)

        /// <summary>
        /// 백그라운드 작업자 작업시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                ResetProgressPanel(0, 100);

                SetProgressPanel("Pasting...", 0);

                ShowProgressPanel();

                #region 소스 텍스트를 설정한다.

                if(this.sourceDataObject == null)
                {
                    return;
                }

                Stream stream = this.sourceDataObject.GetData(DataFormats.CommaSeparatedValue) as Stream;

                if(stream == null)
                {
                    return;
                }

                StreamReader streamReader = new StreamReader(stream, Encoding.GetEncoding("EUC-KR"));

                if(streamReader == null)
                {
                    return;
                }

                string sourceText = streamReader.ReadToEnd().Replace("\0", string.Empty).TrimEnd('\n').TrimEnd('\r');

                if(sourceText == null)
                {
                    this.sourceText = null;
                }
                else
                {
                    sourceText = sourceText.Trim();

                    if(sourceText.Length == 0)
                    {
                        this.sourceText = null;
                    }
                    else
                    {
                        this.sourceText = sourceText;
                    }
                }

                if(this.sourceText == null)
                {
                    return;
                }

                #endregion

                SetProgressPanel("Pasting...", 20);

                #region 소스 리스트를 설정한다.

                List<string[]> sourceList = GetSourceList(this.sourceText);

                if(sourceList == null || sourceList.Count == 0)
                {
                    return;
                }

                #endregion

                SetProgressPanel("Pasting...", 40);

                #region 소스 컬럼 카운트를 설정한다.

                int sourceColumnCount = GetSourceColumnCount(sourceList);

                if(sourceColumnCount < 1)
                {
                    return;
                }

                #endregion
                #region 실제 컬럼 카운트를 설정한다.

                this.actualColumnCount = GetActualColumnCount(this.maximumColumnCount, sourceColumnCount);

                if(this.actualColumnCount < 1)
                {
                    return;
                }

                #endregion
                #region 실제 헤더 텍스트 사용 여부를 설정한다.

                if(this.useHeaderText)
                {
                    this.actualUseHeaderText = ValidateColumnName(sourceList[0], this.actualColumnCount);
                }
                else
                {
                    this.actualUseHeaderText = false;
                }

                #endregion

                SetProgressPanel("Pasting...", 50);

                #region 소스 테이블을 설정한다.

                this.sourceTable = GetSourceTable(sourceList, this.actualUseHeaderText, this.actualColumnCount);

                if(this.sourceTable == null)
                {
                    return;
                }

                #endregion

                SetProgressPanel("Pasting...", 70);

                SetDataGridDataSource();

                SetProgressPanel("Pasting...", 100);

                System.Threading.Thread.Sleep(500);
            }
            catch
            {
                ClearData();
            }
            finally
            {
                HideProgressPanel();
            }
        }

        #endregion
        #region 백그라운드 작업자 작업자 완료시 처리하기 - backgroundWorker_RunWorkerCompleted(sender, e)

        /// <summary>
        /// 백그라운드 작업자 작업자 완료시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.okButton.Enabled     = true;
            this.cancelButton.Enabled = true;
        }

        #endregion
        #region OK 버튼 클릭시 처리하기 - okButton_Click(sender, e)

        /// <summary>
        /// OK 버튼 클릭시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void okButton_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;

            Close();
        }

        #endregion
        #region Cancel 버튼 클릭시 처리하기 - cancelButton_Click(sender, e)

        /// <summary>
        /// Cancel 버튼 클릭시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void cancelButton_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;

            Close();
        }

        #endregion
        #region Delete Selected Rows 메뉴 항목 클릭시 처리하기 - deleteSelectedRowsMenuItem_Click(sender, e)

        /// <summary>
        /// Delete Selected Rows 메뉴 항목 클릭시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void deleteSelectedRowsMenuItem_Click(object sender, EventArgs e)
        {
            ProcessDeleteSelectedRows();
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////// Function

        #region 소스 리스트 구하기 - GetSourceList(sourceText)

        /// <summary>
        /// 소스 리스트 구하기
        /// </summary>
        /// <param name="sourceText">소스 텍스트</param>
        /// <returns>소스 리스트</returns>
        private List<string[]> GetSourceList(string sourceText)
        {
            //if(sourceText == null || sourceText.Length == 0)
            //{
            //    return null;
            //}

            //string[] sourceLineArray = sourceText.Split('\n');
            //int      sourceLineCount = sourceLineArray.Length;

            //List<string[]> sourceList = new List<string[]>();

            //for(int i = 0; i < sourceLineCount; i++)
            //{
            //    string line = sourceLineArray[i].TrimEnd('\r');

            //    if(line == "\0")
            //    {
            //        continue;
            //    }

            //    string[] elementArray = line.Split(',');

            //    sourceList.Add(elementArray);
            //}

            //return sourceList;

            if(sourceText == null || sourceText.Length == 0)
            {
                return null;
            }

            string[] sourceLineArray = sourceText.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            int      sourceLineCount = sourceLineArray.Length;

            List<string[]> sourceList = new List<string[]>();

            for(int i = 0; i < sourceLineCount; i++)
            {
                string line = sourceLineArray[i];

                if(line == "\0")
                {
                    continue;
                }

                string[] elementArray = line.Split(',');
                int      elementCount = elementArray.Length;

                for(int j = 0; j < elementCount; j++)
                {
                    string element = elementArray[j];

                    //element = element.Replace("\n", "\r\n");

                    if(element.Contains("\n"))
                    {
                        element = element.TrimStart('\"').TrimEnd('\"');
                    }

                    elementArray[j] = element;
                }

                sourceList.Add(elementArray);
            }

            return sourceList;
        }

        #endregion
        #region 소스 컬럼 카운트 구하기 - GetSourceColumnCount(sourceList)

        /// <summary>
        /// 소스 컬럼 카운트 구하기
        /// </summary>
        /// <param name="sourceList">소스 리스트</param>
        /// <returns>소스 컬럼 카운트</returns>
        private int GetSourceColumnCount(List<string[]> sourceList)
        {
            int maximumColumnCount = int.MinValue;

            foreach(string[] sourceArray in sourceList)
            {
                int columnCount = sourceArray.Length;

                if(columnCount > maximumColumnCount)
                {
                    maximumColumnCount = columnCount;
                }
            }

            return maximumColumnCount;
        }

        #endregion
        #region 실제 컬럼 카운트 구하기 - GetActualColumnCount(maximumColumnCount, sourceColumnCount)

        /// <summary>
        /// 실제 컬럼 카운트 구하기
        /// </summary>
        /// <param name="maximumColumnCount">최대 컬럼 카운트</param>
        /// <param name="sourceColumnCount">소스 컬럼 카운트</param>
        /// <returns>실제 컬럼 카운트</returns>
        private int GetActualColumnCount(int maximumColumnCount, int sourceColumnCount)
        {
            int actualColumnCount = 0;

            if(maximumColumnCount == -1)
            {
                actualColumnCount = sourceColumnCount;
            }
            else
            {
                if(maximumColumnCount > sourceColumnCount)
                {
                    actualColumnCount = sourceColumnCount;
                }
                else
                {
                    actualColumnCount = maximumColumnCount;
                }
            }

            return actualColumnCount;
        }

        #endregion
        #region 컬럼명 무결성 조사하기 - ValidateColumnName(columnNameArray, actualColumnCount)

        /// <summary>
        /// 컬럼명 무결성 조사하기
        /// </summary>
        /// <param name="columnNameArray">컬럼명 배열</param>
        /// <param name="actualColumnCount">실제 컬럼 카운트</param>
        /// <returns>컬럼명 무결성 조사 결과</returns>
        private bool ValidateColumnName(string[] columnNameArray, int actualColumnCount)
        {
            if(columnNameArray.Length < actualColumnCount)
            {
                return false;
            }

            Dictionary<string, string> dictionary = new Dictionary<string, string>();

            foreach(string columnName in columnNameArray)
            {
                if(dictionary.ContainsKey(columnName))
                {
                    return false;
                }
                else
                {
                    dictionary.Add(columnName, columnName);
                }
            }

            return true;
        }

        #endregion
        #region 비어있는 소스 테이블 구하기 - GetEmptySourceTable(sourceList, actualUseHeaderText, actualColumnCount)

        /// <summary>
        /// 비어있는 소스 테이블 구하기
        /// </summary>
        /// <param name="sourceList">소스 리스트</param>
        /// <param name="actualUseHeaderText">실제 헤더 텍스트 사용 여부</param>
        /// <param name="actualColumnCount">실제 컬럼 카운트</param>
        /// <returns>비어있는 소스 테이블</returns>
        private DataTable GetEmptySourceTable(List<string[]> sourceList, bool actualUseHeaderText, int actualColumnCount)
        {
            DataTable sourceTable = new DataTable();

            if(actualUseHeaderText)
            {
                for(int i = 0; i < actualColumnCount; i++)
                {
                    string columnName = sourceList[0][i];

                    sourceTable.Columns.Add(columnName, typeof(string));
                }
            }
            else
            {
                for(int i = 0; i < actualColumnCount; i++)
                {
                    string columnName = string.Format("Column{0}", i + 1);

                    sourceTable.Columns.Add(columnName, typeof(string));
                }
            }

            return sourceTable;
        }

        #endregion
        #region 소스 테이블 채우기 - FillSourceTable(sourceTable, sourceList, actualUseHeaderText, actualColumnCount)

        /// <summary>
        /// 소스 테이블 채우기
        /// </summary>
        /// <param name="sourceTable">소스 테이블</param>
        /// <param name="sourceList">소스 리스트</param>
        /// <param name="actualUseHeaderText">실제 헤더 텍스트 사용 여부</param>
        /// <param name="actualColumnCount">실제 컬럼 카운트</param>
        private void FillSourceTable(DataTable sourceTable, List<string[]> sourceList, bool actualUseHeaderText, int actualColumnCount)
        {
            int startRow = actualUseHeaderText ? 1 : 0;

            for(int i = startRow; i < sourceList.Count; i++)
            {
                DataRow row = sourceTable.NewRow();

                for(int j = 0; j < actualColumnCount; j++)
                {
                    try
                    {
                        row[j] = sourceList[i][j];
                    }
                    catch
                    {
                    }
                }

                sourceTable.Rows.Add(row);
            }
        }

        #endregion
        #region 소스 테이블 구하기 - GetSourceTable(sourceList, actualUseHeaderText, actualColumnCount)

        /// <summary>
        /// 소스 테이블 구하기
        /// </summary>
        /// <param name="sourceList">소스 리스트</param>
        /// <param name="actualUseHeaderText">실제 헤더 텍스트 사용 여부</param>
        /// <param name="actualColumnCount">실제 컬럼 카운트</param>
        /// <returns>소스 테이블</returns>
        private DataTable GetSourceTable(List<string[]> sourceList, bool actualUseHeaderText, int actualColumnCount)
        {
            if(sourceList == null || sourceList.Count == 0)
            {
                return null;
            }

            DataTable sourceTable = GetEmptySourceTable(sourceList, actualUseHeaderText, actualColumnCount);

            FillSourceTable(sourceTable, sourceList, actualUseHeaderText, actualColumnCount);

            return sourceTable;
        }

        #endregion

        #region 진행 패널 보여주기 - ShowProgressPanel()

        /// <summary>
        /// 진행 패널 보여주기
        /// </summary>
        private void ShowProgressPanel()
        {
            if(this.dataGridView.InvokeRequired)
            {
                SimpleDelegate simpleDelegate = new SimpleDelegate(ShowProgressPanel);

                this.dataGridView.Invoke(simpleDelegate);
            }
            else
            {
                this.progressPanel.Location = new Point
                (
                    (ClientRectangle.Width  - this.progressPanel.Width ) / 2,
                    (ClientRectangle.Height - this.progressPanel.Height) / 2
                );

                this.progressPanel.BringToFront();

                this.progressPanel.Visible = true;
            }
        }

        #endregion
        #region 진행 패널 숨기기 - HideProgressPanel()

        /// <summary>
        /// 진행 패널 숨기기
        /// </summary>
        private void HideProgressPanel()
        {
            if(this.dataGridView.InvokeRequired)
            {
                SimpleDelegate simpleDelegate = new SimpleDelegate(HideProgressPanel);

                this.dataGridView.Invoke(simpleDelegate);
            }
            else
            {
                this.progressPanel.Visible = false;

                this.progressPanel.SendToBack();
            }
        }

        #endregion
        #region 진행 패널 리셋하기 - ResetProgressPanel(minimum, maximum)

        /// <summary>
        /// 진행 패널 리셋하기
        /// </summary>
        /// <param name="minimum">최소값</param>
        /// <param name="maximum">최대값</param>
        private void ResetProgressPanel(int minimum, int maximum)
        {
            if(this.dataGridView.InvokeRequired)
            {
                ResetProgressPanelDelegate resetProgressPanelDelegate = new ResetProgressPanelDelegate(ResetProgressPanel);

                this.dataGridView.Invoke(resetProgressPanelDelegate, minimum, maximum);
            }
            else
            {
                this.progressLabel.Text = string.Empty;

                this.progressBar.Minimum = minimum;
                this.progressBar.Maximum = maximum;
                this.progressBar.Value   = minimum;
            }
        }

        #endregion
        #region 진행 패널 설정하기 - SetProgressPanel(message, value)

        /// <summary>
        /// 진행 패널 설정하기
        /// </summary>
        /// <param name="message">메시지</param>
        /// <param name="value">값</param>
        private void SetProgressPanel(string message, int value)
        {
            if(this.dataGridView.InvokeRequired)
            {
                SetProgressPanelDelegate setProgressPanelDelegate = new SetProgressPanelDelegate(SetProgressPanel);

                this.dataGridView.Invoke(setProgressPanelDelegate, message, value);
            }
            else
            {
                this.progressLabel.Text = message;

                this.progressBar.Value = value;

                this.progressLabel.Update();
                this.progressBar.Update();
            }
        }

        #endregion

        #region 데이터 지우기 - ClearData()

        /// <summary>
        /// 데이터 지우기
        /// </summary>
        private void ClearData()
        {
            if(this.dataGridView.InvokeRequired)
            {
                SimpleDelegate simpleDelegate = new SimpleDelegate(ClearData);

                this.dataGridView.Invoke(simpleDelegate);
            }
            else
            {
                this.actualUseHeaderText   = false;
                this.actualColumnCount     = -1;
                this.sourceDataObject      = null;
                this.sourceText            = null;
                this.sourceTable           = null;
                this.sourceReader          = null;
                this.allowAutoColumnSizing = false;

                this.dataGridView.DataSource = null;
            }
        }

        #endregion
        #region 데이터 설정하기 - SetData()

        /// <summary>
        /// 데이터 설정하기
        /// </summary>
        private void SetData()
        {
            if(!this.backgroundWorker.IsBusy)
            {
                this.okButton.Enabled     = false;
                this.cancelButton.Enabled = false;

                this.backgroundWorker.RunWorkerAsync();
            }
        }

        #endregion
        #region 데이터 그리드 데이터 소스 설정하기 - SetDataGridDataSource()

        /// <summary>
        /// 데이터 그리드 데이터 소스 설정하기
        /// </summary>
        private void SetDataGridDataSource()
        {
            if(this.dataGridView.InvokeRequired)
            {
                SimpleDelegate simpleDelegate = new SimpleDelegate(SetDataGridDataSource);

                this.dataGridView.Invoke(simpleDelegate);
            }
            else
            {
                this.dataGridView.DataSource = this.sourceTable;

                for(int i = 0; i < this.dataGridView.Columns.Count; i++)
                {
                    this.dataGridView.Columns[i].SortMode                  = DataGridViewColumnSortMode.NotSortable;
                    this.dataGridView.Columns[i].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
                }
            }
        }

        #endregion

        #region 컬럼들 자동 크기 조정하기 - AutoResizeColumns()

        /// <summary>
        /// 컬럼들 자동 크기 조정하기
        /// </summary>
        private void AutoResizeColumns()
        {
            if(this.dataGridView.InvokeRequired)
            {
                SimpleDelegate simpleDelegate = new SimpleDelegate(AutoResizeColumns);

                this.dataGridView.Invoke(simpleDelegate);
            }
            else
            {
                if(this.allowAutoColumnSizing)
                {
                    for(int i = 0; i < this.dataGridView.Columns.Count; i++)
                    {
                        this.dataGridView.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.DisplayedCells);
                    }
                }
            }
        }

        #endregion
        #region 행들 자동 크기 조정하기 - AutoResizeRows()

        /// <summary>
        /// 행들 자동 크기 조정하기
        /// </summary>
        private void AutoResizeRows()
        {
            if(this.dataGridView.InvokeRequired)
            {
                SimpleDelegate simpleDelegate = new SimpleDelegate(AutoResizeRows);

                this.dataGridView.Invoke(simpleDelegate);
            }
            else
            {
                if(this.allowAutoRowSizing)
                {
                    for(int i = 0; i < this.dataGridView.Rows.Count; i++)
                    {
                        this.dataGridView.AutoResizeRow(i);
                    }
                }
            }
        }

        #endregion

        #region 선택된 행들 삭제 처리하기 - ProcessDeleteSelectedRows()

        /// <summary>
        /// 선택된 행들 삭제 처리하기
        /// </summary>
        private void ProcessDeleteSelectedRows()
        {
            if(this.dataGridView.SelectedRows == null || this.dataGridView.SelectedRows.Count == 0)
            {
                return;
            }

            DataGridViewSelectedRowCollection collection = this.dataGridView.SelectedRows;

            for(int i = collection.Count; i >= 0; i--)
            {
                DataGridViewRow row = collection[i];

                this.dataGridView.Rows.Remove(row);
            }
        }

        #endregion
        #region 더블 버퍼링 설정하기 - SetDoubleBuffered(control, doubleBuffered)

        /// <summary>
        /// 더블 버퍼링 설정하기
        /// </summary>
        /// <param name="control">컨트롤</param>
        /// <param name="doubleBuffered">더블 버퍼링 여부</param>
        private void SetDoubleBuffered(Control control, bool doubleBuffered)
        {
            Type type = control.GetType();

            PropertyInfo propertyInfo = type.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);

            propertyInfo.SetValue(control, doubleBuffered, null);
        }

        #endregion
    }
}
728x90
반응형
그리드형
Posted by 사용자 icodebroker

댓글을 달아 주세요