반응형

안녕하세요

 

코딩연습생입니다~

 

이번 포스팅은 저번 포스팅에 이어서 C#으로 드라이브 용량을 표시하는 프로그램을 만들어 보겟습니다

 

저번 포스팅에서 기간별 폴더 자동 삭제 프로그램을 만들어 봤었는데 

 

현재 내 드라이브 용량이 얼마나 남았는지 확인하면 좋을거 같아서 이어서 포스팅하게 되엇습니다

 

이전 글을 확인하시고자 한다면 아래 링크를 통해 확인하시면 됩니다

 

https://codingman.tistory.com/122

 

[C#] 기간별 폴더 정리(삭제)하기

안녕하세요 코딩연습생입니다~ 이번 포스팅은 C# 언어로 기간별 폴더를 자동 관리하기 위한 삭제 프로그램을 만들어 볼려고 합니다 [준비과정] 1. Form1을 생성하여 기준일을 생성할 텍스트 박스��

codingman.tistory.com

[준비 과정]

1. 비쥬얼 스튜디오 기본 컨트롤러 필요

   - 포스그레스바(ProgressBar), 레이블(Lable), 버튼(Button)

2. 디자인 폼은 이전 포스팅에서 만든 것을 이용할 예정입니다

 

[디자인]

1. ProgressBar

2. Lable를 통한 명칭 표시 및 용량 표시

3. 버튼을 통한 조회

 

[코딩]

- 조회 버튼 클릭 이벤트 발생시 프로그레스바(ProgressBar)용량 표시 및 Lable 수치 값 표시

1. SetDriveSize 변수 생성

   - 프로그레스바(ProgressBar) 및 Lable 값 생성

        public void SetDriveSize(DriveInfo drive, ProgressBar pb, Label title, Label lb)
        {
            string driveName = string.Empty;
            string totalSize = string.Empty;
            string freeSize = string.Empty;
            string usage = string.Empty;

            try
            {
                driveName = drive.Name.Substring(0, 1).ToString();
                totalSize = Convert.ToInt32(drive.TotalSize / 1024 / 1024 / 1024).ToString();
                freeSize = Convert.ToInt32(drive.AvailableFreeSpace / 1024 / 1024 / 1024).ToString();
                usage = (Convert.ToInt32(totalSize) - Convert.ToInt32(freeSize)).ToString();

                pb.Maximum = Convert.ToInt32(totalSize);
                pb.Value = Convert.ToInt32(usage);

                title.Text = string.Format("Disk ({0}:)", driveName);
                title.AutoSize = true;

                lb.Text = string.Format("{0}GB of {1}GB available.", totalSize, freeSize);
                lb.AutoSize = true;
            }
            catch { }
        }

2. GetDrivesize 변수 생성

   - 조회 할려는 드라이브 찾기

        public void GetDriveSize()
        {
            DriveInfo[] drives = DriveInfo.GetDrives();

            foreach(DriveInfo drive in drives)
            {
                if(drive.DriveType == DriveType.Fixed)
                {
                    if(drive.Name.Contains("D"))
                    {
                        SetDriveSize(drive, progressBar1, label24, label25);
                    }
                }
            }
        }

 

3. 버튼 클릭 이벤트를 통한 호출

        private void customButton7_Click(object sender, EventArgs e)
        {
            if (One_Click())
            {
                GetDriveSize();
            }
        }

 

[실행 결과]

- 조회 버튼 클릭시 지정한 드라이브의 용량을 이렇게 표시 해줍니다

 

- 실제 드라이브 상태

반응형
반응형

안녕하세요

 

코딩연습생입니다~

 

이번 포스팅은 C# 언어로 기간별 폴더를 자동 관리하기 위한 삭제 프로그램을 만들어 볼려고 합니다

 

[준비과정]

1. Form1을 생성하여 기준일을 생성할 텍스트 박스를 생성.

2. 파일 삭제를 실행하기 위한 버튼.

 

[폴더 구조]

- 내문서 -> 대상 폴더(Origin, RESULT_OK, RESULT_NG_ -> 세부 하위 폴더들 존재 -> 일자별 폴더

  ex) C:\Users\Administrator\Documents\ImageLog\대상 폴더\하위 폴더

 

[디자인]

- 디자인은 꼭 똑같이 하실 필요는 없습니다~

- 대상위치는 대상 폴더를 지정하기 위한 콤보박스

- 폴더 List 세부 하위 폴더들을 리스트화 해주는 콤보박스

 

[코딩]

1. 대상 폴더를 지정한 뒤 조회 버튼을 눌러 세부 하위 폴더 리스트를 콤보박스화 시키는 부분

   - path 변수에 경로 변수는 사용하시는 환경에 다라 변경해주셔야 합니다

        private void Path_Combo()
        {
            if (comboBox1.SelectedIndex >= 0)
            {
                string path = textBox_path_to_pcl_vision.Text;
                path = System.IO.Path.Combine(path, "ImageLog");
                path = System.IO.Path.Combine(path, comboBox1.SelectedItem.ToString());

                DirectoryInfo di = new DirectoryInfo(path);
                if (di.Exists == true)
                {
                    DataTable dt = new DataTable();
                    dt.Columns.Add("FolderName", typeof(string));
                    dt.Columns.Add("FolderPath", typeof(string));

                    DataRow ds = null;

                    foreach (var file in di.GetDirectories())
                    {
                        ds = dt.NewRow();
                        ds["FolderName"] = file.Name;
                        ds["FolderPath"] = file.FullName;
                        dt.Rows.Add(ds);
                    }

                    comboBox2.DataSource = dt;
                    comboBox2.ValueMember = "FolderPath";
                    comboBox2.DisplayMember = "FolderName";
                }
            }
            else
            {
                MessageBox.Show("대상위치를 먼저 선택해주세요.");
            }
            
        }

 

- 대상 위치를 설정하고 조회버튼을 누루면 폴더 List 콤보박스에 하위 디렉토리 목록이 보이게 됩니다

*콤보박스에 ValueMember와 DisplayMember 사용 방법은 아래 링크를 통해 알아 보실 수 잇습니다

https://codingman.tistory.com/119

 

[C#] 폴더안의 파일 목록 만들기(리스트박스)

안녕하세요 코딩연습생입니다~ 요즘 코로나도 문제이지만 태풍이 너무 많이 오네요~ 짜증날 정도로ㅎㅎ 글자님들도 코로나 + 태풍 조심하시길 바랍니다 이번 포스팅은 C#으로 리스트박스(ListBox)

codingman.tistory.com

 

- 구동 시킨 모습입니다

 

- 이제 폴더 삭제를 하기 위한 정리 버튼을 하나 생성해주고 코딩을 해보겠습니다

 

- 정리 버튼 클릭 이벤트에 아래와 같이 코딩을 합니다

        public static void deleteFolder(string folderDir)
        {
            try
            {
                Form1 form = new Form1();

                //기본 일수 14일.
                int deleteday = 14;

                //일수를 수동 지정하였을 경우 해당 일수를 가져옴.
                if (form.FolderDay_Period.Text != "")
                {
                    deleteday = Convert.ToInt32(form.FolderDay_Period.Text);
                }
                
                DirectoryInfo di = new DirectoryInfo(folderDir);
                if (di.Exists)
                {
                    DirectoryInfo[] dirInfo = di.GetDirectories();
                    string IDate = DateTime.Today.AddDays(-deleteday).ToString("yyyyMMdd");

                    foreach (DirectoryInfo dir in dirInfo)
                    {
                        if (IDate.CompareTo(dir.LastWriteTime.ToString("yyyyMMdd")) > 0)
                        {
                            dir.Attributes = FileAttributes.Normal;
                            dir.Delete(true);
                        }
                    }
                }

            }
            catch (Exception) { }
        }

 

- 기준 일자를 설정한뒤 정리 버튼을 누루면 

   대상위치의 하위 폴더의 자식 폴더들 중 생성기간을 기준으로 이전 폴더를 삭제 합니다

 

[실행]

- 내문에서 Origin이라는 폴더에 Cam1_Model_1이라는 하위 폴더 내용을 구조는 아래와 같습니다

 

- 정리 버튼을 누루게 되면 수정한 날짜 지금 현재(2020-09-15)이기 때문에 모두 삭제가 되어야 합니다

  기준 일자 설정이 기본 14일로 지정되어 있기 때문에 별도 일자 설정을 하지 않았다면

  모두 삭제가 되는것이 정상이겠죠?

 

 

- 정상 동작하는걸 확인 했습니다

   이 루트를 반복 시행이나 타이머를 통해 자동 실행되도록 한다면 용량 부족 현상을 막을수 있습니다~

반응형
반응형

안녕하세요

 

코딩연습생입니다~

 

요즘 코로나도 문제이지만 태풍이 너무 많이 오네요~ 짜증날 정도로ㅎㅎ

글자님들도 코로나 + 태풍 조심하시길 바랍니다

 

이번 포스팅은 C#으로 리스트박스(ListBox)를 사용하여 폴더내의 파일 목록을 만들고 

 

ValueMember와 DisplayMember를 사용하여 속성값, 보여지기값을 사용하는 방법을 알려드릴려고 합니다

 

물론, 이미 다 아실수도 있지만 저는 머리가 나빠서 기록차원에서 포스팅 할께요~ㅎ

 

일단 첫번째는 버튼을 통해 폴더 지정하는 방법입니다

 

그럼 젤 중요한 버튼이 있어야죠

 

간단하게 저는 폴더라는 이름으로 버튼을 생성했습니다

 

그리고 버튼 Click 이벤트에 아래와 같이 코딩을 했습니다

 

                FolderBrowserDialog dialog = new FolderBrowserDialog();
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                
                }

 

폴더를 선택할 수 있는 Dialog를 띄우기 위함입니다

 

버튼을 누루면 아래와 같은 선택 창이 띄게 되지요

 

그럼 두번째로 폴더를 선택한뒤에 그 폴더안에 있는 하위 파일 목록을 만들어야 합니다

 

그 리스트는 C#의 기본 컨트롤중에 리스트박스(ListBox)를 사용했습니다

 

화면 디자인은 심플합니다

그다음 아까 만들었던 버튼 Click이벤트에 파일 목록을 가져와서 리스트뷰에 뿌려줄수 있게 코딩을 합니다

 

                FolderBrowserDialog dialog = new FolderBrowserDialog();
                if (dialog.ShowDialog() == DialogResult.OK)
                {

                    //불량 이미지 폴더
                    string Folder_Path = dialog.SelectedPath;

                    this.listBox1.Refresh();
                    
                    DirectoryInfo di = new DirectoryInfo(Folder_Path);

                    if (di.Exists == true)
                    {
                        DataTable dt = new DataTable();
                        dt.Columns.Add("FileName", typeof(string));
                        dt.Columns.Add("FullName", typeof(string));

                        DataRow ds = null;

                        foreach (FileInfo file in di.GetFiles())
                        {
                            ds = dt.NewRow();
                            ds["FileName"] = file.Name.Substring(0, file.Name.Length - 4);
                            ds["FullName"] = file.FullName;
                            dt.Rows.Add(ds);
                        }

                        listBox1.DataSource = dt;
                        listBox1.ValueMember = "FullName";
                        listBox1.DisplayMember = "FileName";
                        

                    }
                }

 

여기서 보셔야 할 부분은 DataTable를 생성하여 컬럼을 임의로 생성한 부분

 

                        DataTable dt = new DataTable();
                        dt.Columns.Add("FileName", typeof(string));
                        dt.Columns.Add("FullName", typeof(string));

 

그리고 리스트뷰(ListView)에 DataSource를 사용하여 DataTable값을 넣어주고 ValueMember와 DisplayMember를 

 

사용한 부분

 

                        listBox1.DataSource = dt;
                        listBox1.ValueMember = "FullName";
                        listBox1.DisplayMember = "FileName";

 

이렇게 사용하시게 되면 화면에 보이는 값과 속성 값을 따로 사용하실 수 있습니다

 

 

이렇게 활용하여 사용하실수 있습니다

 

반응형
반응형

안녕하세요

 

코딩연습생입니다~

 

아직 끝나지 않은 코로나로 인해 여간 힘든게 아니네요~

 

여러분들도 모두 코로나 감염으로 부터 조심하시길 바랍니다

 

이번 포스팅은 비쥬얼스튜디오(Microsoft Visual Studio)에서 기본으로 제공되고 있는 데이터그리드뷰(DataGridView)를

 

사용할때 기본 디자인이 너무 구리죠?ㅎㅎ

 

 

갠취이긴 하지만 저는 너무 구리게 느껴집니다 그래서 약간의 설정으로 그래도 조금 있어보이는(?) 그런 그리드뷰로 

 

변경할 수 있는 설정법을 알려드릴려고 합니다

 

비쥬얼스튜디오(Microsoft Visual Studio)를 많이 사용하신분들이면 누구나 알고 계시겠지만 저는 어디까지나

 

초보(?) 아니면 연습생(?) 이런 분들을 위한 포스팅이니 이미 알고 계신분들이라면 뒤로가기를 누루시기 바랍니다ㅎㅎ

 

간혹 이런거 포스팅 하지 말아라 라고 말씀하시는 분들고 계셔서 맘이 아플때가 있어서..ㅠ

 

 

[디자인]

1. C#의 Form에 비쥬얼스튜디오(Microsoft Visual Studio)에서 기본적으로 제공하는 데이터그리드뷰(DataGridView)를 삽입합니다

 

- 삽입하는 방법은 좌측 도구상자탭에서 모든 Windows Forms 항목 중에 DataGridView 컨트롤을 마우스로 드래그앤드롭하여 사입합니다

 

 

2. 삽입된 데이터그리드뷰(DataGridView)를 마우스로 클릭하여 속성창에서 아래와 같이 수정합니다

   - AllowUserToAddRows의 속성을 False로 변경

   - AllowUserToAddRows는 기본상태에서 Rows 한줄을 보여줄것인지 하는것 입니다

   - SelectionMode를 FullRowSelect로 변경

   - 데이터그리드뷰(DataGrideView)의 내용을 선택했을때 선택 방법을 설정합니다

     (사용 용도에 따라 사용하셔도 됩니다)

   - 다음 모양 속성 변경입니다 위에서 아래로 상세 설정 화면입니다

 

   - AlternatingRowsDefaultCell 속성

   - 데이터그리드뷰(DataGrideView)의 내용 부분을 별도 설정없이 Row의 구분 색상을 표현 해줍니다

      (말로 이해가 안되시는분은 제일 마지막 완성 이미지를 보시면 이해 하실겁니다)

 

   - ColumnHeadersDefaultCell 기본 헤더 디자인 변경

   - 헤더의 기본 색생, 정렬, 크기등을 설정합니다

 

   - ★ EnableHeadersVisualStyles 값을 False로 변경

         (해당 옵션을 변경하지 않으면 디자인을 변경하셔도 화면에 표시되지 않습니다)

 

이렇게 기본 데이터그리드뷰(DataGridView) 속성을 몇개를 바꾸고 적용하면 아래와 같이

 

멋있는(?) 그리드뷰로 변경됩니다~

 

 

 

앞서 말씀드렸듯이 어디까지나 갠취입니다;;ㅎㅎ 욕하지 마세요~

반응형
반응형

안녕하세요

 

코딩연습생입니다

 

이번 포스팅은 C#에서 데이터뷰로 많이 사용하는 기본컨트롤러인 데이터 그리드뷰에서

 

엑셀의 자료를 복사하여 붙여넣기 하는 기능을 구현해보고자 합니다

 

장점은 대량의 자료를 한번에 가져올수 있다는게 장점이고

 

단점은 그리드뷰와 엑셀의 셀형식과 구조 같아야하고, 행의 수를 조정해 줘야 한다는게 단점입니다

 

그래도 일단 기초적인 구조를 설명드리고 개선은 여러분의 노력이겠지요?ㅎ

 

[*개발 환경]

- Microsoft Visual Studio 2017

 

신규 폼을 하나 생성하고 그 위에 데이터드리드 뷰 컨트롤러를 배치 합니다

(간단한 부분이라 상세 설명은 생략하고 완성 이미지를 보여드릴께요)

폼 Init부분에 그리드에 대한 속성을 설정 합니다

(저의 폼 이름은 subCustList입니다)

        public subCustList()
        {
            InitializeComponent();

            //데이터그리드뷰 복&붙을 위한 초기 설정.
            this.dataGridView1.AllowUserToDeleteRows = false;
            this.dataGridView1.AllowUserToOrderColumns = true;
            this.dataGridView1.AllowUserToResizeRows = false;
            this.dataGridView1.RowHeadersVisible = false;
            this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect;
            this.dataGridView1.KeyUp += new System.Windows.Forms.KeyEventHandler(this.dataGridView_KeywordBidAmt_KeyUp);
        }

 

다음 KeyUp과 Null값 처리를 위한 함수를 작성 합니다

private void dataGridView_KeywordBidAmt_KeyUp(object sender, KeyEventArgs e)
        {
            //if user clicked Shift+Ins or Ctrl+V (paste from clipboard)
            DataGridView grid = sender as DataGridView;
            if (e.Control && e.KeyCode == Keys.V)
            {
                try
                {
                    char[] rowSplitter = { '\r', '\n' };
                    char[] columnSplitter = { '\t' };
                    int[] columnsOrderArray = dataGridView1.Columns.Cast<DataGridViewColumn>().Where(x => x.Visible).OrderBy(x => x.DisplayIndex).Select(x => x.Index).ToArray();

                    //get the text from clipboard
                    IDataObject dataInClipboard = Clipboard.GetDataObject();
                    string stringInClipboard = (string)dataInClipboard.GetData(DataFormats.Text);

                    //split it into lines
                    string[] rowsInClipboard = stringInClipboard.Split(rowSplitter, StringSplitOptions.RemoveEmptyEntries);

                    //get the row and column of selected cell in grid
                    int r = grid.SelectedCells[0].RowIndex;
                    int c = columnsOrderArray[grid.SelectedCells[0].ColumnIndex];

                    //add rows into grid to fit clipboard lines
                    if (grid.Rows.Count < (r + rowsInClipboard.Length))
                    {
                        grid.Rows.Add(r + rowsInClipboard.Length - grid.Rows.Count);
                    }

                    // loop through the lines, split them into cells and place the values in the corresponding cell.
                    for (int iRow = 0; iRow < rowsInClipboard.Length; iRow++)
                    {
                        //split row into cell values
                        string[] valuesInRow = rowsInClipboard[iRow].Split(columnSplitter);

                        //cycle through cell values
                        for (int iCol = 0; iCol < valuesInRow.Length; iCol++)
                        {
                            //assign cell value, only if it within columns of the grid
                            if (columnsOrderArray.Count() - 1 >= c + iCol)
                            {
                                int idx = columnsOrderArray[c + iCol];
                                grid.Rows[r + iRow].Cells[idx].Value = valuesInRow[iCol];
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("알 수 없는 데이터 형식입니다. Excel에서 복사 후 붙여넣기해주세요" + Environment.NewLine + ex.Message);
                }
            }

            if (e.KeyCode == Keys.Delete)
            {
                foreach (DataGridViewCell cell in grid.SelectedCells)
                {
                    //선택된 Cell을 모두 null로 변경해버린다.
                    cell.Value = null;
                }

                NullDataGridViewRowDelete(grid);
            }

        }

        private void NullDataGridViewRowDelete(DataGridView dgv)
        {
            //아 머리아파서 짜기 귀찮어 그냥 맨뒤꺼인 추가안된에 제외하고 나머지 모두삭제 이때 역순으로 해야지 인덱스안꼬여
            List<DataGridViewRow> temp = dgv.Rows.Cast<DataGridViewRow>().Where(x => x.Cells.Cast<DataGridViewCell>().Where(y => y.Value == null || string.IsNullOrEmpty(y.Value.ToString())).Count() == x.Cells.Count).ToList();
            for (int i = temp.Count() - 2; i >= 0; i--)
            {
                dgv.Rows.RemoveAt(temp[i].Index);
            }
        }

 

그리고 버튼을 통해 Row를 추가 하는 기능을 만듭니다

 

제일 상단 부분에 DataTable를 하나 선언합니다

 

private DataTable dt;

 

그리고 버튼을 하나 생성하고 버튼 클릭 이벤트에 다음과 같이 작성합니다

 

                        dt = new DataTable();
                        dt = dataGridView1.DataSource as DataTable;
                        string[] row0 = { "", "", "", "", "", "", "", "", "", "", "" };
                        dt.Rows.Add(row0);
                        dataGridView1.DataSource = dt;

 

추가 버튼을 통한 Row가 추가된 화면

버튼을 눌러 붙여넣기 할 만큼의 Row를 미리 생성한뒤에 붙여 넣기 하면 그리드뷰에 데이터가 붙여넣기가 됩니다

 

 

Ctl + V를 통해 붙여넣기 된 화면

 

이상 C#에서 데이터그리드뷰에 Clipboard를 이용한 붙여넣기 구현 방법이였습니다

 

감사합니다~

반응형
반응형

안녕하세요

 

코딩연습생입니다

 

이번 포스팅은 C# WINFORM에서 데이터드리트뷰(DataGridView)를 사용하실때

 

뷰안에서 값 변경이 일어났을때 이벤트를 캣치해서 행위를 할려고 할때 해당 뷰의 내용의 셀(Cell)이 콤보 박스 일 경우

 

에는 이벤트가 먹질 않습니다

 

그래서 이런 경우 이벤트를 발생시킬수 있는 방법을 알려드리고자 합니다

 

이미 많은 분들이 알고 계실듯 한데 언제나 처럼 기록과 혹시나 모를 분들을 위해 포스팅 합니다

 

보통 데이터그리드뷰에서 값 변경 이벤트로 사용되는 이벤트 함수는 

 

CellValueChanged() 함수를 사용하는데요 다른 타입의 셀은 모두 반응하는데 이상하게 콤보박스만 반응하지 않습니다

 

 

이럴때는 다음과 같이 이벤트를 걸어주면 사용할 수 있습니다

 

첫번째 이벤트 함수는 EditingControlShowing() 함수 입니다

 

 

위와 같이 이벤트를 생성하시고 다음과 같이 콤보 박스에 아이템을 설정해 줍니다

 

private void sGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (sGridView1.CurrentCell.ColumnIndex == 3)
            {
                int rowIndex = this.sGridView1.CurrentCell.RowIndex;
                string y1Name = this.sGridView1.Rows[rowIndex].Cells[3].Value as string;

                ComboBox comboBox = e.Control as ComboBox;

                if (comboBox != null)
                {
                    object value = comboBox.SelectedItem;
                    comboBox.SelectedIndexChanged -= comboBox_SelectedIndexChanged;
                    comboBox.Items.Clear();

                    if (y1Name.Length > 0)
                    {
                        comboBox.Items.AddRange(new object[] { "Y", "N" });
                    }

                    comboBox.SelectedItem = value;

                    comboBox.SelectedIndexChanged += comboBox_SelectedIndexChanged;
                }
            }
        }

 

그리고 EditingControlShowing() 함수가  동작했을때 정의한 콤보박스에 SelectdIndexChanged 함수가 동작하게 합니다

 

 private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (sGridView1.CurrentCell.RowIndex >= 0)
                {
                    if (sGridView1.CurrentCell.ColumnIndex == 3)
                    {
                        if (sGridView1.Rows[sGridView1.CurrentCell.RowIndex].Cells[5].Value != null)
                        {
                            this.sGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
                            this.sGridView1.UpdateCellValue(sGridView1.CurrentCell.ColumnIndex, sGridView1.CurrentCell.RowIndex);
							
                            //이벤트 발생시 동작할 내용 부분
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
            }
        }

 

위의 comboBox_SelectedIndexChanged() 함수는 직접 타이핑해서 생성하였습니다

 

마지막으로 CellClick() 함수 입니다

 

 

생성된 CellClick() 함수에 아래와 같이 코딩을 합니다

        private void sGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if ((e.RowIndex < 0) || (e.ColumnIndex < 0))
            {
                return;
            }

            if (e.ColumnIndex != 0)
            {
                return;
            }

            DataGridViewRow dataGridViewRow = this.sGridView1.Rows[e.RowIndex];
            DataGridViewCell dataGridViewCell = dataGridViewRow.Cells[e.ColumnIndex];
            
            if (dataGridViewCell is DataGridViewComboBoxCell)
            {
                sGridView1.CurrentCell = dataGridViewCell;
                sGridView1.BeginEdit(true);

                DataGridViewComboBoxEditingControl comboboxEdit = (DataGridViewComboBoxEditingControl)this.sGridView1.EditingControl;

                if (comboboxEdit != null)
                {
                    comboboxEdit.DroppedDown = true;
                }
            }
        }

 

동작 순서는 이렇습니다 데이터 그리드뷰의 컨트롤에서 셀 클릭이벤트가 발생하게 되면 EditingControlShowing()를

 

호출하게 되어 콤보박스가 동작 할 수 있도록 이벤트를 활성화 해주구요

 

콤보박스가 동작한뒤에 값이 변경되는것이 감지 되어지면 comboBox_SelectedIndexChanged()가 호출되어 지는 겁니다

 

이렇게 하시면 데이터드리드뷰에서도 콤보박스의 값 변경 이벤트를 사용할수 있게 됩니다

 

디버깅 모드 상태에서 아래 그림처럼 그리드 뷰의 콤보 박스의 값을 변경하게 되면

이렇게 중단점이 걸리는 걸 보실수 있습니다

 

 

반응형
반응형

안녕하세요

 

코딩연습생입니다

 

이번 포스팅 주제는 투명 팝업창을 이용한 ProgressBar 만들기 입니다

 

프로그래스바란?

.NET에서 진행율을 표기하기 위한 그래픽 컨트롤 입니다

 

비쥬얼스튜디오의 도구 모음에 기본 도구로 있는데요

 

대충 이렇게 생긴 모습입니다

 

흔히 프로그램을 사용하다보면 업데이트나 데이터 처리를 할때 사용자에게 얼마큼 진행되었는지를 알려주기위해

 

사용합니다

 

이런 컨트롤을 팝업창을 통해 메인 Form위에 투명으로 띄워 진행 여부를 표시해주는 팝업을 생성해볼려고 합니다

 

일단 팝어창을 만들기 위해 From을 하나 생성합니다

 

그리고 생성된 폼 속정에서 TransparencyKey를 배경색과 동일하게 설정 합니다

 

이렇게 설정하시면 해당 폼이 팝업으로 띄워졌을때 주변 배경이 투명으로 처리되어 보여지게 됩니다

 

그리고 무언가 처리중인걸 표시하기 위해 픽쳐박스 컨트롤에 GIF 파일을 넣어 줄겁니다

 

PictureBox 컨트롤을 팝업 폼에 생성하고 그림박스의 배경 이미지를 GIF 파일로 넣어줍니다

 

참고로 진행 상태 GIF는 아래 링크 페이지를 활용하시면 됩니다

 

https://www.sitepoint.com/demos/loading-images/

 

AJAX Loading Images Collections | SitePoint

 

www.sitepoint.com

 

여기까지 설정을 하셨다면 아래와 같은 화면이 구성 될겁니다

 

 

그럼 cs코드 안으로 들어가서 아래와 같이 Using을 선언 합니다

 

using System.Threading;
using System.Runtime.InteropServices;
using System.Resources;

 

쓰레드는 GIF를 움직이기 위해 필요하고

 

인터럽트서비스는 팝업창을 핸들링하기 위해 필요합니다

 

그리고 마지막 리소스는 GIF를 등록하게 되면 이미지가 리소스로 들어가기 때문에 선언 햇습니다

 

public partial class SplashWnd : Form
    {
        Bitmap bit;

        #region Static Function
        /// 
        /// 스플래쉬 닫을 때 true로 세팅하는 값
        /// 
        private static bool isCloseCall = false;

        /// 
        /// 스플래쉬 띄우기
        /// 
        public static void SplashShow()
        {
            System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
            Control mainWindow = Control.FromHandle(process.MainWindowHandle);

            isCloseCall = false;
            Thread thread = new Thread(new ParameterizedThreadStart(ThreadShowWait));
            thread.Start(new object[] { mainWindow });
        }

        /// 
        /// 스플래쉬 닫기
        /// 
        /// 스플래쉬를 닫은 후 맨 앞으로 가져올 폼
        public static void SplashClose(Form formFront)
        {
            //Thread의 loop 를 멈춘다.
            isCloseCall = true;

            //주어진 폼을 맨 앞으로
            SetForegroundWindow(formFront.Handle);
            formFront.BringToFront();
        }

        /// 

        /// 윈도우를 맨 앞으로 가져오기 위한 Win32 API 메서드
        /// 
        /// 윈도우 핸들
        /// 
        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        /// 

        /// 스플래쉬를 띄우기 위한 Parameterized Thread Method
        /// 
        /// 메인 윈도(위치를 잡기 위해)
        private static void ThreadShowWait(object obj)
        {
            object[] objParam = obj as object[];
            SplashWnd splashWnd = new SplashWnd();
            Control mainWindow = objParam[0] as Control;

            if (mainWindow != null)
            {
                //메인 윈도를 알 때에는 메인 윈도의 중앙
                splashWnd.StartPosition = FormStartPosition.Manual;
                splashWnd.Location = new Point(
                    mainWindow.Location.X + (mainWindow.Width - splashWnd.Width) / 2,
                    mainWindow.Location.Y + (mainWindow.Height - splashWnd.Height) / 2);
            }
            else
            {
                //메인 윈도를 모를 땐 스크린 중앙
                splashWnd.StartPosition = FormStartPosition.CenterScreen;
            }

            splashWnd.Show();
            splashWnd.BringToFront();

            //닫기 명령이 올 때 가지 0.01 초 단위로 루프
            while (!isCloseCall)
            {
                Application.DoEvents();
                Thread.Sleep(10);
            }

            //닫는다.
            if (splashWnd != null)
            {
                splashWnd.CloseForce();
                splashWnd = null;
            }
        }

        #endregion Static Function


        #region SplashWnd Member, Function, Event

        /// 

        /// 값이 true 이면 창이 닫히지 않음.
        /// 
        private bool cannotClose = true;

        /// 

        /// 생성자
        /// 
        public SplashWnd()
        {
            InitializeComponent();

            //투명도는 줘도 되고 안 줘도 되고
            this.Opacity = 0.7f;

        }

        /// 

        /// 사용자가 ALT+F4 등의 키로 닫는 걸 방지
        /// 
        /// 
        protected override void OnClosing(CancelEventArgs e)
        {
            if (cannotClose)
            {
                e.Cancel = true;
                return;
            }

            base.OnClosing(e);
        }

        /// 

        /// 이 메서드를 호출해야만 창이 닫힌다.
        /// 
        public void CloseForce()
        {
            //OnClose 에서 닫힐 수 있도록 세팅
            cannotClose = false;
            this.Close();
        }
        #endregion SplashWnd Member, Function, Event

        protected override void OnLoad(EventArgs e)
        {
            ResourceManager rm = Properties.Resources.ResourceManager;
            Bitmap normal = (Bitmap)rm.GetObject("loading14");
            bit = new Bitmap(normal);
            ImageAnimator.Animate(bit, new EventHandler(this.OnFrameChanged));
            base.OnLoad(e);

        }

        protected override void OnPaint(PaintEventArgs e)
        {
            ImageAnimator.UpdateFrames();
            Graphics g = pictureBox1.CreateGraphics();
            g.DrawImage(this.bit, new Point(0, 0));
            base.OnPaint(e);
        }

        private void OnFrameChanged(object sender, EventArgs e)
        {
            this.Invalidate();
        }
    }

 

그 다음 ProgressBar를 사용하시고자 하는 위치에서

 

SplashWnd.SplashShow();

 

구분을 사용해서 팝업을 생성해주고

 

진행이 끝난뒤 아래 구분을 통해 팝업창을 해제 합니다

 

SplashWnd.SplashClose(this);

 

사용자가 내가 만든 프로그램 안에서 어떤 행위가 진행 될때 알려주기 위한 표시기 역할로 만들것이기 때문에

 

프로그램에서 행위가 일어나기전과 끝난뒤에 위의 구문을 넣어주면 무언가 진행되어지는것을 알려줄수 있습니다

 

반응형
반응형

안녕하세요

 

코딩 연습생 입니다

 

이전 포스팅에서 직접 엑셀의 API를 활용하여 엑셀파일의 내용을 불러와 데이터그리드뷰와 연동하는 포스팅을

 

업로드했었는데요

 

https://codingman.tistory.com/100

 

[C#] 엑셀 템플릿파일 불러오기 및 값 넣기

안녕하세요 코딩 연습생입니다 아직도 코로나19로 인해서 기업들 소상인 분들 모두 참 어렵게 지내고 계시는거 같습니다 저 또한 회사원으로 회사가 많이 힘들어 지고 있다고 체감할 정도니깐요 그래도 국가에서..

codingman.tistory.com

 

이전 포스팅 방식으로 직접 구현을 해보신 분이나 관련 내용을 아시는분들이라면 아실것 같은데요

 

위의 방법으로 구현했을시(직접 엑셀을 임포트하는 방식) 제일 큰 단점은 대량을 엑셀 파일을 읽을때

 

엄청 느리다는것 입니다

 

그것을 조금이나마 해결하고자 엑셀의 문서 속성을 변경하여 이용하는데

 

https://codingman.tistory.com/101

 

[C#] 엑셀 Cells 사용시 속도 문제 해결하기

안녕하세요. 코딩연습생입니다. 정말 오랜만에 글을 쓰는거 같습니다.. 회사 프로젝트 진행 때문에 시간을 너무 빼앗겨 버리네요ㅎㅎ 근데 저도 이제 블로거가 다 된거 같습니다 하루에도 몇번씩 포스팅 걱정을 하..

codingman.tistory.com

 

이것도 전에 포스팅했었네요ㅎㅎ 근데 이 방법도 미미한 차이일뿐 사용자는 크게 느끼지 못합니다

 

그래서 이번에 포스팅할 내용은 직접 엑셀을 임포는하는 방식이 아닌 OleDbConnection을 이용한 엑셀 연동 방식으로

 

구현을 해볼려고 합니다

 

아마 이미 정보가 많이 있어서 한번쯤 구현을 해보시지 않았을까 싶은데요

 

하나씩 쉽게 이해할수 있도록 순서대로 포스팅해보도록 할께요

 

첫번재는 해당 From에서 OleDb를 사용하기 위한 선언부 입니다

 

아마 닷넷 4버전 이상을 사용하시는분이라면 기본적으로 포함되어 있을건데

 

혹시 프로젝트의 참조부분에 System.Data가 있는지 확인한 후에 없으시면 참조추가를 사용해서 추가해 줍니다

 

 

그리고 From의 제일 상단위에 다음과 같이 선언을 합니다

 

using System.Data.OleDb;

 

사실 윈도우에서 기본 사용이 가능해야 하는데 오류가 발생을 많이 합니다

 

그래서 사전 배포를 용이하게 하기 위해서 몇가지 설치 파일을 설치 해야합니다

 

해당 패키지를 설치 하지 않고 배포 하시면

 

"Microsoft.ACE.OLEDB.12.0 공급자는 로컬 컴퓨터에 등록할 수 없습니다.(System.Data)"

위와 같은 오류를 경험하게 되십니다ㅎㅎ

 

저와 같은 경험을 하지 않게 해드리기 위해서 미리 패키지 설치까지 합니다

 

http://www.microsoft.com/ko-kr/download/details.aspx?id=13255

 

Microsoft Access Database Engine 2010 재배포 가능 패키지

이 다운로드를 실행하면 2010 Microsoft Office System 파일과 Microsoft Office가 아닌 다른 응용 프로그램 사이에서 데이터를 쉽게 전송할 수 있는 구성 요소 집합이 설치됩니다.

www.microsoft.com

위의 주소로 접속해서 32비트 & 64비트 설치 파일을 모두 설치 해주세요

 

그다음 비쥬얼스튜디오로 돌아와서 From에 버튼을 하나 생성해 줍니다

 

저는 기존 소스를 이용하겠습니다

 

 

이렇게 버튼을 하나 준비해 주시구요

 

버튼의 Click 이벤트를 만들어 주세요

 

만드신 이벤트안에 아래의 소스코드를 만들어 줍니다

 

private void hoverGradientButton10_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "엑셀 파일 선택하세요";
            openFileDialog.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
            DialogResult result = openFileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                SubForms.SplashWnd.SplashShow();

                this.Cursor = Cursors.WaitCursor;
                //엑셀 앱
                Excel.Application app = new Excel.Application();
                app.DisplayAlerts = false;
                app.Visible = false;
                app.ScreenUpdating = false;
                app.DisplayStatusBar = false;
                app.EnableEvents = false;

                Excel.Workbooks workbooks = app.Workbooks;

                //엑셀 워크북(파일경로읽어서)
                //Excel.Workbook workbook = workbooks.Open(openFileDialog.FileName);
                Excel.Workbook workbook = workbooks.Open(openFileDialog.FileName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                // 엑셀 워크싯 객체
                Excel.Sheets sheets = workbook.Worksheets;
                Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);

                // 엑셀파일 이름이 나온다
                string excelFileName = workbook.Name;
                //excelFileName = excelFileName.Substring(book.Name.Length-3);
                string[] str = excelFileName.Split('.');
                // 워크시트 첫번째 이름
                string workSheetName = worksheet.Name;

                try
                {
                    if (str[1].Equals("xls"))
                    {
                        // 연결 string
                        string constr = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='"
                      + openFileDialog.FileName + "';Extended Properties=Excel 8.0;";

                        //경로까지 다 포함해서 .xls라고 뜨네;
                        //MessageBox.Show(openFileDialog.FileName);

                        // excel conn
                        OleDbConnection conn = new OleDbConnection(constr);

                        // excel cmd
                        OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + workSheetName + "$]", conn);
                        conn.Open();

                        OleDbDataAdapter sda = new OleDbDataAdapter(cmd);
                        DataTable dt = new DataTable();
                        sda.Fill(dt);
                        this.Cursor = Cursors.WaitCursor;
                        dataGridView1.DataSource = dt;
                        this.Cursor = Cursors.Default;
                        conn.Close();


                    }
                    else if (str[1].Equals("xlsx"))
                    {
                        // 연결 string
                        String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                        openFileDialog.FileName +
                        ";Extended Properties='Excel 12.0 XML;HDR=No;IMEX=1';";

                        //경로까지 다 포함해서 .xls라고 뜨네;
                        //MessageBox.Show(openFileDialog.FileName);

                        // excel conn
                        OleDbConnection conn = new OleDbConnection(constr);

                        // excel cmd
                        OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + workSheetName + "$]", conn);
                        conn.Open();

                        OleDbDataAdapter sda = new OleDbDataAdapter(cmd);
                        DataTable dt = new DataTable();
                        sda.Fill(dt);

                        int j = 0;
                        //dataGridView1.DataSource = dt;
                        for(int i=6; i<=dt.Rows.Count-1; i++)
                        {
                            
                            dataGridView2.Rows.Add(1);
                            dataGridView2.Rows[j].Cells[0].Value = dt.Rows[i][0].ToString();
                            dataGridView2.Rows[j].Cells[1].Value = dt.Rows[i][2].ToString();
                            dataGridView2.Rows[j].Cells[2].Value = dt.Rows[i][4].ToString();
                            dataGridView2.Rows[j].Cells[3].Value = dt.Rows[i][5].ToString();
                            dataGridView2.Rows[j].Cells[4].Value = dt.Rows[i][6].ToString();
                            dataGridView2.Rows[j].Cells[5].Value = dt.Rows[i][7].ToString();
                            dataGridView2.Rows[j].Cells[6].Value = dt.Rows[i][8].ToString();
                            dataGridView2.Rows[j].Cells[7].Value = dt.Rows[i][9].ToString();
                            dataGridView2.Rows[j].Cells[8].Value = dt.Rows[i][10].ToString();
                            dataGridView2.Rows[j].Cells[9].Value = dt.Rows[i][11].ToString();
                            dataGridView2.Rows[j].Cells[10].Value = dt.Rows[i][12].ToString();
                            dataGridView2.Rows[j].Cells[11].Value = dt.Rows[i][13].ToString();
                            dataGridView2.Rows[j].Cells[12].Value = dt.Rows[i][14].ToString();
                            dataGridView2.Rows[j].Cells[13].Value = dt.Rows[i][15].ToString();
                            dataGridView2.Rows[j].Cells[14].Value = dt.Rows[i][16].ToString();
                            dataGridView2.Rows[j].Cells[15].Value = dt.Rows[i][17].ToString();
                            dataGridView2.Rows[j].Cells[16].Value = dt.Rows[i][18].ToString();
                            dataGridView2.Rows[j].Cells[17].Value = dt.Rows[i][19].ToString();
                            dataGridView2.Rows[j].Cells[18].Value = dt.Rows[i][20].ToString();
                            dataGridView2.Rows[j].Cells[19].Value = dt.Rows[i][21].ToString();
                            dataGridView2.Rows[j].Cells[20].Value = dt.Rows[i][22].ToString();
                            dataGridView2.Rows[j].Cells[21].Value = dt.Rows[i][23].ToString();
                            dataGridView2.Rows[j].Cells[22].Value = dt.Rows[i][24].ToString();
                            dataGridView2.Rows[j].Cells[23].Value = dt.Rows[i][25].ToString();
                            dataGridView2.Rows[j].Cells[24].Value = dt.Rows[i][26].ToString();
                            dataGridView2.Rows[j].Cells[25].Value = dt.Rows[i][27].ToString();
                            dataGridView2.Rows[j].Cells[26].Value = dt.Rows[i][28].ToString();
                            dataGridView2.Rows[j].Cells[27].Value = dt.Rows[i][29].ToString();
                            dataGridView2.Rows[j].Cells[28].Value = dt.Rows[i][30].ToString();
                            dataGridView2.Rows[j].Cells[29].Value = dt.Rows[i][31].ToString();
                            dataGridView2.Rows[j].Cells[30].Value = dt.Rows[i][32].ToString();
                            dataGridView2.Rows[j].Cells[31].Value = dt.Rows[i][33].ToString();
                            dataGridView2.Rows[j].Cells[32].Value = dt.Rows[i][34].ToString();
                            dataGridView2.Rows[j].Cells[33].Value = dt.Rows[i][35].ToString();
                            dataGridView2.Rows[j].Cells[34].Value = dt.Rows[i][36].ToString();
                            dataGridView2.Rows[j].Cells[35].Value = dt.Rows[i][37].ToString();
                            dataGridView2.Rows[j].Cells[36].Value = dt.Rows[i][38].ToString();
                            dataGridView2.Rows[j].Cells[37].Value = dt.Rows[i][39].ToString();
                            dataGridView2.Rows[j].Cells[38].Value = dt.Rows[i][40].ToString();
                            dataGridView2.Rows[j].Cells[39].Value = dt.Rows[i][41].ToString();
                            dataGridView2.Rows[j].Cells[40].Value = dt.Rows[i][42].ToString();
                            dataGridView2.Rows[j].Cells[41].Value = dt.Rows[i][43].ToString();
                            dataGridView2.Rows[j].Cells[42].Value = dt.Rows[i][44].ToString();
                            dataGridView2.Rows[j].Cells[43].Value = dt.Rows[i][45].ToString();
                            dataGridView2.Rows[j].Cells[44].Value = dt.Rows[i][46].ToString();
                            dataGridView2.Rows[j].Cells[45].Value = dt.Rows[i][47].ToString();
                            dataGridView2.Rows[j].Cells[46].Value = dt.Rows[i][48].ToString();
                            dataGridView2.Rows[j].Cells[47].Value = dt.Rows[i][49].ToString();
                            dataGridView2.Rows[j].Cells[48].Value = dt.Rows[i][50].ToString();
                            dataGridView2.Rows[j].Cells[49].Value = dt.Rows[i][51].ToString();
                            dataGridView2.Rows[j].Cells[50].Value = dt.Rows[i][52].ToString();
                            dataGridView2.Rows[j].Cells[51].Value = dt.Rows[i][53].ToString();
                            dataGridView2.Rows[j].Cells[52].Value = dt.Rows[i][54].ToString();
                            dataGridView2.Rows[j].Cells[53].Value = dt.Rows[i][55].ToString();
                            dataGridView2.Rows[j].Cells[54].Value = dt.Rows[i][56].ToString();
                            dataGridView2.Rows[j].Cells[55].Value = dt.Rows[i][57].ToString();
                            dataGridView2.Rows[j].Cells[56].Value = dt.Rows[i][58].ToString();
                            dataGridView2.Rows[j].Cells[57].Value = dt.Rows[i][59].ToString();
                            dataGridView2.Rows[j].Cells[58].Value = dt.Rows[i][60].ToString();
                            dataGridView2.Rows[j].Cells[59].Value = dt.Rows[i][61].ToString();
                            dataGridView2.Rows[j].Cells[60].Value = dt.Rows[i][62].ToString();
                            dataGridView2.Rows[j].Cells[61].Value = dt.Rows[i][63].ToString();
                            dataGridView2.Rows[j].Cells[62].Value = dt.Rows[i][64].ToString();
                            dataGridView2.Rows[j].Cells[63].Value = dt.Rows[i][65].ToString();
                            dataGridView2.Rows[j].Cells[64].Value = dt.Rows[i][66].ToString();
                            dataGridView2.Rows[j].Cells[65].Value = dt.Rows[i][67].ToString();
                            dataGridView2.Rows[j].Cells[66].Value = dt.Rows[i][68].ToString();
                            dataGridView2.Rows[j].Cells[67].Value = dt.Rows[i][69].ToString();
                            dataGridView2.Rows[j].Cells[68].Value = dt.Rows[i][70].ToString();
                            dataGridView2.Rows[j].Cells[69].Value = dt.Rows[i][71].ToString();
                            dataGridView2.Rows[j].Cells[70].Value = dt.Rows[i][72].ToString();
                            dataGridView2.Rows[j].Cells[71].Value = dt.Rows[i][73].ToString();
                            dataGridView2.Rows[j].Cells[72].Value = dt.Rows[i][74].ToString();
                            dataGridView2.Rows[j].Cells[73].Value = dt.Rows[i][75].ToString();
                            dataGridView2.Rows[j].Cells[74].Value = dt.Rows[i][76].ToString();
                            dataGridView2.Rows[j].Cells[75].Value = dt.Rows[i][77].ToString();
                            dataGridView2.Rows[j].Cells[76].Value = dt.Rows[i][78].ToString();
                            dataGridView2.Rows[j].Cells[77].Value = dt.Rows[i][79].ToString();
                            dataGridView2.Rows[j].Cells[78].Value = dt.Rows[i][80].ToString();
                            dataGridView2.Rows[j].Cells[79].Value = dt.Rows[i][81].ToString();
                            dataGridView2.Rows[j].Cells[80].Value = dt.Rows[i][82].ToString();
                            dataGridView2.Rows[j].Cells[81].Value = dt.Rows[i][83].ToString();
                            
                            j++;
                        }

                        this.Cursor = Cursors.Default;
                        conn.Close();

                        Finish_Data_Insert();
                        SubForms.SplashWnd.SplashClose(this);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    workbook.Close(true, null, null);
                    app.Quit();

                    ReleaseExcelObject(worksheet);
                    ReleaseExcelObject(sheets);
                    ReleaseExcelObject(workbook);
                    ReleaseExcelObject(workbooks);
                    ReleaseExcelObject(app);
                }
                finally
                {
                    workbook.Close(true, null, null);
                    app.Quit();

                    ReleaseExcelObject(worksheet);
                    ReleaseExcelObject(sheets);
                    ReleaseExcelObject(workbook);
                    ReleaseExcelObject(workbooks);
                    ReleaseExcelObject(app);
                }
            }
        }

 

오브젝트 초기화를 위해 아래 함수로 하나 작성해 줍니다

 

private void ReleaseExcelObject(object obj)
        {
            try
            {
                if (obj != null)
                {
                    Marshal.ReleaseComObject(obj);
                    obj = null;
                }
            }
            catch (Exception ex)
            {
                obj = null;
                throw ex;
            }
            finally
            {
                GC.Collect();
            }
        }

 

이렇게 해주시고 생성하신 버튼을 누구게 되면 OpenFileDialog가 열리고 거기서 엑셀 파일을 선택해 주시면

 

해당 엑셀의 문서 내용이 데이터그리드뷰에 옴겨지게 됩니다

 

위의 소스 내용중 "SubForms.SplashWnd.SplashShow();" 구문은 주석 또는 삭제 하셔도 무관합니다

 

해당 코드는 사용자에게 진행중을 표시하기 위한 ProgressBar를 구현한것인데 없어도 구동하는데 전혀 문제가 없습니다

 

해당 내용은 다른 포스팅에서 정리해서 올리도록 할께요

 

이전 방식과 현재의 방식을 모두 구현을 하셨다면 속도 비교를 해보시면 깜짝 놀라실수 있을겁니다

 

동일 엑셀 문서기준 (대략 Row가 1000개)의 파일을 불러오기 하였을때

 

기존방식 : 10~15분 소요

현재방식 : 30초 미만

 

엄청난 차이를 보여주더라구요

 

엑셀과 연동을 구현하기 위해 고민중이시라면 위의 방법을 통해 구현해 보시길 바랍니다

반응형

+ Recent posts