본문 바로가기

프로젝트/DataGridView XML 데이타 베이스 프로그램

C# XML 데이타베이스 구조 관리 프로그램 소스코드 (3)

 

//

//         제작자  :  신 옥 진

//          

//          스스로 수정 안한 단순 재배포는  금지, 그냥 링크를 사용 하세요.  

//          수정후 배포시 원 제작자 표시 삭제 금지 및  댓글로 알려주세요. ( 예의)

//

//           영리목적(  유료 강의 자료, 판매 시스템에 포함 등 )의 사용은 사전 허락을 받아야 합니다.

//

using System;
using System.Data;
using System.IO;
using System.Windows.Forms;

/// 연구중 ///

namespace XML_DBM
{
    public partial class frmMain : Form
    {
 public static bool 한글사용 = true;  // 전역변수  
        bool Working         = false;  //false  대기중 // true  작업중       
        bool DataSet_NoEdit  = true;   // 변경된 내용이 없음

        DataSet ds;      // 작업중 DataSet        
        string  df;      // 작업중 파일 FilePath       
        string  wf = Application.StartupPath;  // 작업디렉토리

        // Form관련      
        public frmMain() { InitializeComponent(); }// end func
        private void frmMain_Load(object sender, EventArgs e)
        {
            ControlEnable();         // Control enabled 설정
            DataSet_NoEdit = true;   // 현 DataSet에 변경사항 없음 
        }// end func
        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!DataSet_NoEdit)   // 현DataSet에 변경 상황이 있다면
            {
                FormYesNo frm = new FormYesNo();     // 저장유무 묻기 Dialog
                DialogResult re = frm.ShowDialog();
                if (re == DialogResult.Cancel) e.Cancel = true;// 취소 Return
                if (re == DialogResult.Yes) btSave_Click(null, null);  // 저장
            }
        }//func

       
        // 버튼관련
        private void btDataSet_Click(object sender, EventArgs e)
        {
            if (txtDataSet.Text == "") return; //공백이면
            if (!Working)   // 작업대기중 
            {
                Working = true; //--> 작업중 변경 
                btDataSet.Text = radio한글.Checked ? "초기화" : "Initialization";
                ds = new DataSet(txtDataSet.Text);
            }
            else  // 작업중
            {
                if (!DataSet_NoEdit) //변경내용 있음
                {
                    FormYesNo frm = new FormYesNo();
                    DialogResult re = frm.ShowDialog();
                    if (re == DialogResult.Cancel) return;
                    if (re == DialogResult.Yes) btSave_Click(null, null);
                }
                Working = false;  // --> 작업대기중 변경 
                btDataSet.Text = radio한글.Checked ? "새로생성" : "New DSet";
                ds.Dispose();
                txtDataSet.Text = "";
                txtTable.Text = "";
                cbTable.Items.Clear();
                listField.Items.Clear();
                this.Text = "XML File 만들기";

            }
            ControlEnable();
            DataSet_NoEdit = true;
        }// end func
        private void btTableAdd_Click(object sender, EventArgs e)
        {
            if (txtTable.Text == "") return; //공백이면
            if (cbTable.Items.Contains(txtTable.Text)) return; //기존Table이면

            cbTable.Items.Add(txtTable.Text);     //목록추가      
            cbTable.SelectedIndex = cbTable.Items.IndexOf(txtTable.Text);
            ds.Tables.Add(txtTable.Text);
            txtTable.Text = "";
            listField.Items.Clear();
            DataSet_NoEdit = false;
            ControlEnable();
        }// end func
        private void btTableDel_Click(object sender, EventArgs e)
        {           
            if (ck경고.Checked)  //  삭제경고 체크 상태이면
            {
                FormDelCaution frm = new FormDelCaution();
                DialogResult re = frm.ShowDialog();
                if (re == DialogResult.Cancel) return;
            }

            listField.Items.Clear();             // 필드list 모두제거
            ds.Tables.Remove(cbTable.Text);      // Table제거
            cbTable.Items.Remove(cbTable.Text);  // 목록제거          
            if (cbTable.Items.Count > 0)         // 안 비어 있어면   
                 cbTable.SelectedIndex = 0;      // 첫 목록선택           
            else cbTable.Text = "";              // 목록 선택 안함
           
            DataSet_NoEdit = false;     // 변경내용 있음
            ControlEnable();
        }// end func
        private void btTableRename_Click(object sender, EventArgs e)
        {
            if (txtTable.Text == "") return; //공백이면
            if (cbTable.Items.Contains(txtTable.Text)) return;//기존Table이면
            
            ds.Tables[cbTable.Text].TableName = txtTable.Text; //이름변경
            cbTable.Items.Remove(cbTable.Text);  // 목록제거
            cbTable.Items.Add(txtTable.Text);    // 목록삽입                
            cbTable.SelectedIndex = cbTable.Items.IndexOf(txtTable.Text); // 새목록 선택                        
            txtTable.Text = "";
            DataSet_NoEdit = false;
            ControlEnable();
        }// end func

        private void btAdd_Click(object sender, EventArgs e)
        {
            if (txtField.Text == "") return; //공백이면
            if (listField.Items.Contains(txtField.Text)) return;//기존필드면

            listField.Items.Add(txtField.Text);            // 목록추가
            DataTable dt = ds.Tables[cbTable.Text];        // 현재 테이블
            dt.Columns.Add(txtField.Text, typeof(string)); // 필드 추가
            if (dt.Rows.Count != 0)           //    빈테이블이 아니라면
                foreach (DataRow row in dt.Rows) //  모든 레코드(행)의
                    row[txtField.Text] = "";  //해당 필드를 빈문자열로 설정
            else
            {                              // 빈 테이블이면
                DataRow r = dt.NewRow();   // 새로운 빈 레코드(행)을 만듬                                           // 
                r[txtField.Text] = "";     // 빈 테이블은
                dt.Rows.Add(r);            // 저장시 테이블 사라짐 
            }
            txtField.Text = "";
            DataSet_NoEdit = false;
            ControlEnable();           
        }// end func
        private void btDel_Click(object sender, EventArgs e)
        {
            if (listField.SelectedIndex == -1) return; //범위밖이면
            if (ck경고.Checked)  //  삭제경고 체크 상태이면
            {                
                FormDelCaution frm = new FormDelCaution();
                DialogResult re = frm.ShowDialog();
                if (re == DialogResult.Cancel) return;
            }
            DataTable dt = ds.Tables[cbTable.Text];
            dt.Columns.RemoveAt(listField.SelectedIndex);
            listField.Items.RemoveAt(listField.SelectedIndex);

            DataSet_NoEdit = false; 
            ControlEnable();
        }// end func
        private void btInsert_Click(object sender, EventArgs e)
        {
            if (txtField.Text == "") return; // 공백이면
            if (listField.SelectedIndex == -1) return; //범위밖이면
            if (listField.Items.Contains(txtField.Text)) return; //기존필드면

            int index = listField.SelectedIndex;  // 삽입위치
            btAdd_Click(null, null);              // 컬렉션 맨 뒤에 필드추가
            int index2 = listField.Items.Count-1; // 추가된 필드 인덱스
            listField.SelectedIndex = index2;     // 추가된 필드를 Selected 
            for( int i=0; i< index2 - index; i++) // 삽입위치로 필드 이동
                          btUp_Click(null, null);
            
            txtField.Text = "";
            DataSet_NoEdit = false;
            ControlEnable();
        }// end func
        private void btSave_Click(object sender, EventArgs e)
        {
            menu다른이름저장_Click(null, null);
        }// end func
        private void btLoad_Click(object sender, EventArgs e)
        {
            if (!DataSet_NoEdit)
            {
                FormYesNo frm = new FormYesNo();
                DialogResult re = frm.ShowDialog();
                if (re == DialogResult.Cancel) return;
                if (re == DialogResult.Yes) btSave_Click(null, null);
            }

            openFileDialog.InitialDirectory = wf;   //프로그램 실행 파일 위치
            openFileDialog.FileName = "*.xml";
            openFileDialog.Filter = "xml files (*.xml)|*.txt|All files (*.*)|*.*";

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                df = openFileDialog.FileName;
                wf = df.Substring(0, df.Length - 4);
                this.Text = "XML File Manager for C# DataGrid : " + openFileDialog.SafeFileName; ;
                cbTable.Items.Clear();
                listField.Items.Clear();                
                if (ds != null) ds.Dispose();  // DataSet 삭제
                ds = new DataSet();
                ds.ReadXml(df);

                txtDataSet.Text = ds.DataSetName;

                foreach (DataTable t in ds.Tables)
                            cbTable.Items.Add(t.TableName);
                cbTable.SelectedIndex = 0;
                Working = true;
                ControlEnable();
                DataSet_NoEdit = true;
            }
        }// end func
        private void btUp_Click(object sender, EventArgs e)
        {
            int index = listField.SelectedIndex;
            if (index <= 0) return; //처음위치 또는 범위밖
            string Item = listField.SelectedItem.ToString();          // 대상필드명
            string frontItem = listField.Items[index - 1].ToString(); //앞에 필드명
           
            listField.Items[index - 1] = Item;   // 서로 필드명 바꾸기
            listField.Items[index] = frontItem;

            DataTable dt = ds.Tables[cbTable.Text];       // 현재 테이블
            dt.Columns[index].ColumnName = "동일필드방지";// 필드명 교환을 위해 임시로(""안됨)
            dt.Columns[index - 1].ColumnName = Item;      // 같은 필드명이 있어면
            dt.Columns[index].ColumnName = frontItem;     // 에러가 남
            changeField(index - 1, index); // 데이타를 서로 교환 해주는 함수
            listField.SelectedIndex = index - 1;  // 이동한 위치를 선택
            DataSet_NoEdit = false;
            ControlEnable();
        }// end func
        private void btDown_Click(object sender, EventArgs e)
        {
            int index = listField.SelectedIndex;
            if (index == -1) return;      //  범위밖
            if (index > listField.Items.Count - 2) return; //마지막위치
            string Item = listField.SelectedItem.ToString();
            string backItem = listField.Items[index + 1].ToString();

            listField.Items[index] = backItem;  // 리스트에서 필드명 교환
            listField.Items[index + 1] = Item;
           

            DataTable dt = ds.Tables[cbTable.Text];  // 테이블에서 필드명 교환
            dt.Columns[index].ColumnName = "tempName";
            dt.Columns[index + 1].ColumnName = Item;
            dt.Columns[index].ColumnName = backItem;
            changeField(index, index + 1); // 인자1 < 인자2 가 되게 배치
            listField.SelectedIndex = index + 1;  //이동한 위치를 선택
            DataSet_NoEdit = false;
            ControlEnable();
        }// end func
        private void btRename_Click(object sender, EventArgs e)
        {
            if (txtField.Text == "") return; //공백이면
            if (listField.SelectedIndex == -1) return; //인덱스 범위밖
            if (listField.Items.Contains(txtField.Text)) return; //기존필드

            int index = listField.SelectedIndex;  //인덱스위치
            listField.Items[index]=txtField.Text; // 리스트에서 필드명 변경
            ds.Tables[cbTable.Text].Columns[index].ColumnName = txtField.Text;
                                  // 테이블에서 리스트명 변경
            txtField.Text = "";
            DataSet_NoEdit = false;
            ControlEnable();
        }

        // 메뉴관련
        private void menuExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }// end func
        private void menuAbout_Click(object sender, EventArgs e)
        {
            FormAbout frm = new FormAbout();
            frm.ShowDialog();
        }// end func
        private void menu다른이름저장_Click(object sender, EventArgs e)
        {
            saveFileDialog.InitialDirectory = wf;   //프로그램 실행 파일 위치
            saveFileDialog.FileName = "*.xml";
            saveFileDialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*";

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {

                if (File.Exists(df))
                {
                    try { File.Delete(df.Substring(0, df.Length - 3) + "bak"); } catch { }
                    File.Copy(df, df.Substring(0, df.Length - 3) + "bak");                   
                }
                df = saveFileDialog.FileName;
                wf = df.Substring(0, df.Length - 4);
                ds.WriteXml(df);
                this.Text = "XML File 만들기 - " + df.Substring(df.LastIndexOf('\\') + 1);
            }              // 파일경로에서 마지막 '\'의 인덱스 구한후 그다음 문자열 가져오면 순수 파일명

            DataSet_NoEdit = true;
            return;
        }
        // ETC......
        private void cbTable_SelectedIndexChanged(object sender, EventArgs e)
        {       
            listField.Items.Clear();
            try
            {
                foreach (DataColumn c in ds.Tables[cbTable.Text].Columns)
                    listField.Items.Add(c.ToString());
            }
            catch { }
            bool b = DataSet_NoEdit;
            ControlEnable();
            DataSet_NoEdit = b;
        }// end func       


        private void ControlEnable()
        {
           DataSet_NoEdit = false;

            btTableDel.Visible   = ck삭제버튼.Checked && cbTable.Items.Count != 0;
            btDel.Visible            = ck삭제버튼.Checked && listField.Items.Count != 0;                       
            txtTable.Visible       = Working;
            btTableAdd.Visible = Working;


            bool TF = cbTable.Items.Count != 0;
            {
                ck삭제버튼.Checked = ck삭제버튼.Checked && TF;
                btTableRename.Visible = TF;
                txtField.Visible = TF;
                btSave.Visible = TF;
                menuSave.Visible = TF;
                btAdd.Visible = TF;
                cbTable.Visible = TF;
            }
            TF = listField.Items.Count > 0;
            {
                btInsert.Visible = TF;
                btRename.Visible = TF;
            }
            
            TF = listField.Items.Count > 1;
            {
                btUp.Visible = TF;
                btDown.Visible = TF;
            }

        } // end func       

 

    private void changeField(int index, int index2)       

    {
            DataTable dt = ds.Tables[cbTable.Text];
            DataRow tempItem = dt.NewRow();      // 교환을 의한 임시 buffer

            for (int r = 0; r < dt.Rows.Count; r++)  // 모든 레코드(행)를 대상으로
            {                                        //foreach는 읽을 때만 변경이 안됨                   
                tempItem[0] = dt.Rows[r][index];     // 교체전 index data 백업
                dt.Rows[r][index] = dt.Rows[r][index2];
                dt.Rows[r][index2] = tempItem[0];
            }
        }
        private void ck삭제버튼_CheckedChanged(object sender, EventArgs e)
        {
            if ( (listField.Items.Count + cbTable.Items.Count) == 0) ck삭제버튼.Checked = false;            
            ck삭제버튼.ForeColor = ck삭제버튼.Checked ?                                                           

                                                                    Sysm.Drawing.Color.Red : System.Drawing.Color.Black;
            btTableDel.Visible = ck삭제버튼.Checked && cbTable.Items.Count != 0;
            btDel.Visible = ck삭제버튼.Checked && listField.Items.Count != 0;   
        }
        private void ck경고_CheckedChanged(object sender, EventArgs e)
        {
            ck경고.ForeColor = ck경고.Checked ? System.Drawing.Color.Red : System.Drawing.Color.Black;
        }


        private void radio한글_CheckedChanged(object sender, EventArgs e)
        {
            한글사용 = radio한글.Checked;
            if (한글사용)
            {
                btAdd.Text = "추가";
                btDel.Text = "삭제";
                btInsert.Text = "삽입";
                btLoad.Text = "불러오기";
                btRename.Text = "변경";
                btSave.Text = "저장하기";
                btTableAdd.Text = "추가";
                btTableDel.Text = "삭제";
                btTableRename.Text = "변경";
                ck경고.Text = "삭제경고표시";
                ck삭제버튼.Text = "삭제버튼사용";
                btDataSet.Text = Working ? "초기화" : "새로생성";

                menuExit.Text = "종료";
                menuLoad.Text = "읽어오기";
                menuSave.Text = "저장하기";
                menu다른이름저장.Text = "다른이름으로 저장하기";
                tmenuHelp.Text = "도움말";
                tmenu파일.Text = "파일";
            }
            else
            {
                btAdd.Text = "Add";
                btDel.Text = "Del";
                btInsert.Text = "Insert";
                btLoad.Text = "Load";
                btRename.Text = "Rename";
                btSave.Text = "Save";
                btTableAdd.Text = "Add";
                btTableDel.Text = "Del";
                btTableRename.Text = "Rename";
                ck경고.Text = "Del Warning";
                ck삭제버튼.Text = "Del Enable";
                btDataSet.Text = Working ? "Iinitialization" : "New DSet";

                menuExit.Text = "Exit";
                menuLoad.Text = "Load File";
                menuSave.Text = "Save File";
                menu다른이름저장.Text = "Save File AS";
                tmenuHelp.Text = "Help";
                tmenu파일.Text = "File";
            }

        }//func
    }//frmMain

}//namespace


      using System;
using System.Windows.Forms;

namespace XML_DBM
{
    public partial class FormAbout : Form
    {
        public FormAbout()
        {
            InitializeComponent();
        }

        private void btOk_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void FormAbout_Load(object sender, EventArgs e)
        {
            // 속성에서 startposition을 center parent로 변경하먄 됨
            // this.StartPosition = FormStartPosition.CenterParent;
        }
    }
}


using System.Windows.Forms;

namespace XML_DBM
{
    public partial class FormYesNo : Form
    {
        public FormYesNo()
        {
            InitializeComponent();
        }

        private void btNo_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.No;
            Close();
        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        private void btYes_Click(object sender, EventArgs e)
        {
            DialogResult = (DialogResult)DialogResult.Yes;
            Close();
        }

        private void FormYesNo_Load(object sender, EventArgs e)
        {
            if (frmMain.한글사용) 
            {
                label1.Text = "작업내용을 저장 할까요 ?";
                bt아니오.Text = "아니오";
                bt취소.Text = "취소";
                bt저장.Text = "저장";
            } 
            else
            {
                label1.Text = "Shall I save the DataSet ?";
                bt아니오.Text = "No";
                bt취소.Text = "Cancel";
                bt저장.Text = "Save";
            }
        }
    }
}


using System;
using System.Windows.Forms;


namespace XML_DBM
{
    public partial class FormDelCaution : Form
    {
        public FormDelCaution()
        {
            InitializeComponent();
        }

        private void FormDelCaution_Load(object sender, EventArgs e)
        {
           if( frmMain.한글사용 )
            {
                label1.Text = "삭제시 해당 필드 데이타\n\n 손실됨";
                label2.Text = "복구는 즉시 백업파일을 사용하세요";
                bt삭제.Text = "삭제";
                bt취소.Text = "취소";
            }
           else
            {
                label1.Text = "Loss of that field data\n\n when deleted";
                label2.Text = "Use the backup file immediately for recovery";
                bt삭제.Text = "Delete";
                bt취소.Text = "Cancel";
            }
        }

        private void btOK_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
            Close();
        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }
    }
}