■ SQLite 데이터베이스를 사용해 CRUD 처리하기

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

기본 데이터 처리를 위한 학습 교재로 작성되어 실제 업무 처리 코드에 비해 단순화 되었다.

 


TestProject.zip


TestModel.cs

 

 

using System;

 

namespace TestProject

{

    /// <summary>

    /// 테스트 모델

    /// </summary>

    public class TestModel

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Property

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

 

        #region ID - ID

 

        /// <summary>

        /// ID

        /// </summary>

        public string ID { get; set; }

 

        #endregion

        #region 제목 - Subject

 

        /// <summary>

        /// 제목

        /// </summary>

        public string Subject { get; set; }

 

        #endregion

        #region 사용 여부 - UseYN

 

        /// <summary>

        /// 사용 여부

        /// </summary>

        public string UseYN { get; set; }

 

        #endregion

        #region 생성 시간 - CreateDate

 

        /// <summary>

        /// 생성 시간

        /// </summary>

        public DateTime CreateDate { get; set; }

 

        #endregion

        #region 수정 시간 - UpdateDate

 

        /// <summary>

        /// 수정 시간

        /// </summary>

        public DateTime UpdateDate { get; set; }

 

        #endregion

    }

}

 

 

EditMode.cs

 

 

namespace TestProject

{

    /// <summary>

    /// 편집 모드

    /// </summary>

    public enum EditMode

    {

        /// <summary>

        /// Normal

        /// </summary>

        Normal,

 

        /// <summary>

        /// Search

        /// </summary>

        Search,

 

        /// <summary>

        /// Add

        /// </summary>

        Add,

 

        /// <summary>

        /// Update

        /// </summary>

        Update

    }

}

 

 

QueryHelper.cs

 

 

using System;

using System.Collections.Generic;

using System.Data;

using System.Data.SQLite;

using System.Windows.Forms;

 

namespace TestProject

{

    /// <summary>

    /// 쿼리 헬퍼

    /// </summary>

    public static class QueryHelper

    {

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

        ////////////////////////////////////////////////////////////////////////////////////////// Static

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

 

        #region Field

 

        /// <summary>

        /// 연결

        /// </summary>

        private static string _connection = $@"URI=file:{Application.StartupPath}\test.db";

 

        #endregion

 

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

        ////////////////////////////////////////////////////////////////////////////////////////// Static

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

 

        #region 항목 추가하기 - InsertItem(connection, source)

 

        /// <summary>

        /// 항목 추가하기

        /// </summary>

        /// <param name="connection">연결</param>

        /// <param name="source">소스</param>

        public static void InsertItem(SQLiteConnection connection, TestModel source)

        {

            using(SQLiteCommand command = new SQLiteCommand(connection))

            {

                command.CommandText = @"

INSERT INTO Test

(

    ID

   ,Subject

   ,UseYN

   ,CreateDate

   ,UpdateDate

)

VALUES

(

    @ID

   ,@Subject

   ,@UseYN

   ,DATETIME('NOW', 'LOCALTIME')

   ,DATETIME('NOW', 'LOCALTIME')

)

";

                command.Parameters.Add(new SQLiteParameter(@"ID"     , DbType.String) { Value = source.ID                            });

                command.Parameters.Add(new SQLiteParameter(@"Subject", DbType.String) { Value = source.Subject                       });

                command.Parameters.Add(new SQLiteParameter(@"UseYN"  , DbType.String) { Value = source.UseYN ?? (object)DBNull.Value });

 

                command.ExecuteNonQuery();

            }

        }

 

        #endregion

        #region 항목 추가하기 - InsertItem(source)

 

        /// <summary>

        /// 항목 추가하기

        /// </summary>

        /// <param name="source">소스</param>

        public static void InsertItem(TestModel source)

        {

            using(SQLiteConnection connection = new SQLiteConnection(_connection))

            {

                connection.Open();

 

                using(SQLiteCommand command = new SQLiteCommand(connection))

                {

                    InsertItem(connection, source);

                }

            }

        }

 

        #endregion

        #region 항목 수정하기 - UpdateData(source)

 

        /// <summary>

        /// 항목 수정하기

        /// </summary>

        /// <param name="source">소스</param>

        public static void UpdateItem(TestModel source)

        {

            using(SQLiteConnection connection = new SQLiteConnection(_connection))

            {

                connection.Open();

 

                using(SQLiteCommand command = new SQLiteCommand(connection))

                {

                    command.CommandText = @"

UPDATE Test

SET

    SUBJECT    = @Subject

  , UseYN      = @UseYN

  , UpdateDate = DATETIME('NOW', 'LOCALTIME')

WHERE ID = @ID

";

 

                    command.Parameters.Add(new SQLiteParameter(@"ID"     , DbType.String) { Value = source.ID                            });

                    command.Parameters.Add(new SQLiteParameter(@"Subject", DbType.String) { Value = source.Subject                       });

                    command.Parameters.Add(new SQLiteParameter(@"UseYN"  , DbType.String) { Value = source.UseYN ?? (object)DBNull.Value });

 

                    command.ExecuteNonQuery();

                }

            }

        }

 

        #endregion

        #region 항목 삭제하기 - DeleteItem(id)

 

        /// <summary>

        /// 항목 삭제하기

        /// </summary>

        /// <param name="id">ID</param>

        public static void DeleteItem(string id)

        {

            using(SQLiteConnection connection = new SQLiteConnection(_connection))

            {

                connection.Open();

 

                using(SQLiteCommand command = new SQLiteCommand(connection))

                {

                    command.CommandText = "DELETE FROM Test WHERE ID = @ID";

 

                    command.Parameters.Add(new SQLiteParameter(@"ID", DbType.String) { Value = id });

 

                    command.ExecuteNonQuery();

                }

            }

        }

 

        #endregion

 

        #region 리스트 구하기 - GetList(id, subject, UseYN, createDate1, createDate2)

 

        /// <summary>

        /// 리스트 구하기

        /// </summary>

        /// <param name="id">ID</param>

        /// <param name="subject">제목</param>

        /// <param name="UseYN">사용 여부</param>

        /// <param name="createDate1">생성일 1</param>

        /// <param name="createDate2">생성일 2</param>

        public static List<TestModel> GetList(string id, string subject, string UseYN, string createDate1, string createDate2)

        {

            using(SQLiteConnection connection = new SQLiteConnection(_connection))

            {

                connection.Open();

 

                using(SQLiteCommand command = new SQLiteCommand(connection))

                {

                    command.CommandText = @"

SELECT

    A.ID         AS ID

   ,A.Subject    AS Subject

   ,A.UseYN      AS UseYN

   ,A.CreateDate AS CreateDate

   ,A.UpdateDate AS UpdateDate

FROM Test A

WHERE (@ID      = A.ID      OR A.ID      IS NULL OR A.ID      LIKE @ID      || '%')

AND   (@Subject = A.Subject OR A.Subject IS NULL OR A.Subject LIKE @Subject || '%')

AND   (@UseYN   = A.UseYN   OR A.UseYN   IS NULL OR A.UseYN   LIKE @UseYN   || '%')

AND   ((CreateDate BETWEEN @CreateDate1 AND @CreateDate2 + 1           ) OR

       (@CreateDate1 =  ''         AND @CreateDate2 =  ''              ) OR

       (@CreateDate1 =  ''         AND CreateDate   <= @CreateDate2 + 1) OR

       (@CreateDate1 <= CreateDate AND @CreateDate2 =  ''              ))

";

 

                    command.Parameters.Add(new SQLiteParameter(@"ID"         , DbType.String) { Value = id          });

                    command.Parameters.Add(new SQLiteParameter(@"Subject"    , DbType.String) { Value = subject     });

                    command.Parameters.Add(new SQLiteParameter(@"UseYN"      , DbType.String) { Value = UseYN       });

                    command.Parameters.Add(new SQLiteParameter(@"CreateDate1", DbType.String) { Value = createDate1 });

                    command.Parameters.Add(new SQLiteParameter(@"CreateDate2", DbType.String) { Value = createDate2 });

 

                    SQLiteDataReader reader = command.ExecuteReader();

 

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

 

                    while(reader.Read())

                    {

                        TestModel item = new TestModel();

 

                        item.ID         =                    reader["ID"        ].ToString();

                        item.Subject    =                    reader["Subject"   ].ToString();

                        item.UseYN      =                    reader["UseYN"     ].ToString();

                        item.CreateDate = Convert.ToDateTime(reader["CreateDate"]);

                        item.UpdateDate = Convert.ToDateTime(reader["UpdateDate"]);

 

                        list.Add(item);

                    }

 

                    return list;

                }

            }

        }

 

        #endregion

        #region 항목 구하기 - GetItem(id)

 

        /// <summary>

        /// 항목 구하기

        /// </summary>

        /// <param name="id">ID</param>

        /// <returns>항목</returns>

        public static TestModel GetItem(string id)

        {

            using(SQLiteConnection connection = new SQLiteConnection(_connection))

            {

                connection.Open();

 

                using(SQLiteCommand command = new SQLiteCommand(connection))

                {

                    command.CommandText = @"

SELECT

    A.ID         AS ID

   ,A.Subject    AS Subject

   ,A.UseYN      AS UseYN

   ,A.CreateDate AS CreateDate

   ,A.UpdateDate AS UpdateDate

FROM Test A

WHERE A.ID = @ID

";

 

                    command.Parameters.Add(new SQLiteParameter(@"ID", DbType.String) { Value = id });

 

                    SQLiteDataReader reader = command.ExecuteReader();

 

                    while(reader.Read())

                    {

                        TestModel test = new TestModel();

 

                        test.ID         =                    reader["ID"        ].ToString();

                        test.Subject    =                    reader["Subject"   ].ToString();

                        test.UseYN      =                    reader["UseYN"     ].ToString();

                        test.CreateDate = Convert.ToDateTime(reader["CreateDate"]);

                        test.UpdateDate = Convert.ToDateTime(reader["UpdateDate"]);

 

                        return test;

                    }

 

                    return null;

                }

            }

        }

 

        #endregion

    }

}

 

 

CustomFormatter.cs

 

 

using System;

 

namespace TestProject

{

    /// <summary>

    /// 사용 여부 포매터

    /// </summary>

    public class UseYNFormatter : IFormatProvider, ICustomFormatter

    {

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

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

 

        #region 포맷 구하기 - GetFormat(formatType)

 

        /// <summary>

        /// 포맷 구하기

        /// </summary>

        /// <param name="formatType">포맷 타입</param>

        /// <returns>객체</returns>

        public object GetFormat(Type formatType)

        {

            return this;

        }

 

        #endregion

        #region 포맷 값 구하기 - Format(formatString, sourceValue, formatProvider)

 

        /// <summary>

        /// 포맷 값 구하기

        /// </summary>

        /// <param name="formatString">포맷 문자열</param>

        /// <param name="sourceValue">소스 값</param>

        /// <param name="formatProvider">포맷 제공자</param>

        /// <returns>포맷 값</returns>

        public string Format(string formatString, object sourceValue, IFormatProvider formatProvider)

        {

            string value = sourceValue.ToString();

 

            if(sourceValue.Equals("Y"))      return "예";

            else if(sourceValue.Equals("N")) return "아니오";

            else                             return value;

        }

 

        #endregion

    }

}

 

 

DevexpressHelper.cs

 

 

using DevExpress.XtraEditors;

 

namespace TestProject

{

    /// <summary>

    /// DevExpress 헬퍼

    /// </summary>

    public class DevexpressHelper

    {

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

        ////////////////////////////////////////////////////////////////////////////////////////// Static

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

 

        #region 콤보 박스 에디터 초기화 하기 - ClearComboBoxEdit(comboBoxEdit)

 

        /// <summary>

        /// 콤보 박스 에디터 초기화 하기

        /// </summary>

        /// <param name="comboBoxEdit">콤보 박스 에디터</param>

        public static void ClearComboBoxEdit(ComboBoxEdit comboBoxEdit)

        {

            comboBoxEdit.Properties.Items.Clear();

        }

 

        #endregion

        #region 콤보 박스 에디터 데이터 설정하기 - SetComboBoxEditData(sourceControl, itemValueArray)

        

        /// <summary>

        /// 콤보 박스 에디터 데이터 설정하기

        /// </summary>

        /// <param name="comboBoxEdit">콤보 박스 에디터</param>

        /// <param name="itemValueArray">항목 값 배열</param>

        public static void SetComboBoxEditData(ComboBoxEdit comboBoxEdit, params string[] itemValueArray)

        {

            foreach(string itemValue in itemValueArray)

            {

                comboBoxEdit.Properties.Items.Add(itemValue);

            }

        }

 

        #endregion

    }

}

 

 

MainForm.cs

 

 

using System;

using System.Collections.Generic;

using System.Windows.Forms;

 

using DevExpress.Utils;

using DevExpress.XtraEditors;

using DevExpress.XtraEditors.Controls;

using DevExpress.XtraGrid.Columns;

using DevExpress.XtraGrid.Views.Base;

 

namespace TestProject

{

    /// <summary>

    /// 메인 폼

    /// </summary>

    public partial class MainForm : XtraForm

    {

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

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

 

        #region Field

        

        /// <summary>

        /// 편집 모드

        /// </summary>

        private EditMode editMode = EditMode.Normal;

 

        /// <summary>

        /// 소스 리스트

        /// </summary>

        private List<TestModel> sourceList = null;

 

        #endregion

 

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

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

 

        #region 생성자 - MainForm()

 

        /// <summary>

        /// 생성자

        /// </summary>

        public MainForm()

        {

            InitializeComponent();

 

            #region 조회 사용 여부 콤보 박스 에디터를 설정합니다.

 

            DevexpressHelper.ClearComboBoxEdit(this.searchUseYNComboBoxEdit);

 

            DevexpressHelper.SetComboBoxEditData(this.searchUseYNComboBoxEdit, "", "예", "아니오");

 

            this.searchUseYNComboBoxEdit.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;

 

            #endregion

            #region 리스트 그리드 뷰를 설정합니다.

 

            this.listGridView.Appearance.HeaderPanel.Font = Font;

            this.listGridView.Appearance.Row.Font         = Font;

 

            this.listGridView.OptionsView.ShowGroupPanel          = false;

            this.listGridView.OptionsBehavior.AutoPopulateColumns = false;

            this.listGridView.OptionsView.ColumnAutoWidth          = false;

            this.listGridView.OptionsBehavior.Editable              = false;

 

            this.listGridView.Columns.Add(GetGridColumn("ID"        , "ID"        , "ID"       , 300, true));

            this.listGridView.Columns.Add(GetGridColumn("Subject"   , "Subject"   , "제목"     , 200, true));

            this.listGridView.Columns.Add(GetGridColumn("UseYN"     , "UseYN"     , "사용 여부", 100, true));

            this.listGridView.Columns.Add(GetGridColumn("CreateDate", "CreateDate", "생성 시간", 180, true));

            this.listGridView.Columns.Add(GetGridColumn("UpdateDate", "UpdateDate", "수정 시간", 180, true));

 

            this.listGridView.Columns["CreateDate"].DisplayFormat.FormatType   = FormatType.DateTime;

            this.listGridView.Columns["CreateDate"].DisplayFormat.FormatString = "yyyy-MM-dd HH:MM:ss";

            this.listGridView.Columns["UpdateDate"].DisplayFormat.FormatType   = FormatType.DateTime;

            this.listGridView.Columns["UpdateDate"].DisplayFormat.FormatString = "yyyy-MM-dd HH:MM:ss";

 

            this.listGridView.Columns["UseYN"].DisplayFormat.Format = new UseYNFormatter();

 

            #endregion

            #region 사용 여부 콤보 박스 에디터를 설정합니다.

 

            DevexpressHelper.ClearComboBoxEdit(this.useYNComboBoxEdit);

 

            DevexpressHelper.SetComboBoxEditData(this.useYNComboBoxEdit, "", "예", "아니오");

 

            #endregion

            #region 이벤트를 설정합니다.

 

            this.searchButton.Click             += searchButton_Click;

            this.listGridView.FocusedRowChanged += listGridView_FocusedRowChanged;

            this.addButton.Click                += addButton_Click;

            this.updateButton.Click             += updateButton_Click;

            this.deleteButton.Click             += deleteButton_Click;

            this.okButton.Click                 += okButton_Click;

            this.cancelButton.Click             += cancelButton_Click;

 

            #endregion

 

            SetListGridControlData(new List<TestModel>());

 

            SetEditMode(EditMode.Normal);

        }

 

        #endregion

 

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

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

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

 

        #region 조회 버튼 클릭시 처리하기 - searchButton_Click(sender, e)

 

        /// <summary>

        /// 조회 버튼 클릭시 처리하기

        /// </summary>

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

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

        private void searchButton_Click(object sender, EventArgs e)

        {

            try

            {

                SetEditMode(EditMode.Search);

 

                string searchID          = this.searchIDTextEdit.Text.Trim();

                string searchSubject     = this.searchSubjectTextEdit.Text.Trim();

                string searchUseYN       = GetUseYN(this.searchUseYNComboBoxEdit);

                string searchCreateDate1 = this.searchCreateDateEdit2.Text;

                string searchCreateDate2 = this.searchCreateDateEdit1.Text;

 

                SetListGridControlData(null);

 

                List<TestModel> sourceList = QueryHelper.GetList(searchID, searchSubject, searchUseYN, searchCreateDate1, searchCreateDate2);

 

                SetListGridControlData(sourceList);

            }

            catch(Exception exception)

            {

                MessageBox.Show(exception.ToString());

            }

            finally

            {

                SetEditMode(EditMode.Normal);

            }

        }

 

        #endregion

        #region 리스트 그리드 뷰 포커스 행 변경시 처리하기 - listGridView_FocusedRowChanged(sender, e)

 

        /// <summary>

        /// 리스트 그리드 뷰 포커스 행 변경시 처리하기

        /// </summary>

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

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

        private void listGridView_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)

        {

            TestModel focusItem = this.listGridView.GetFocusedRow() as TestModel;

 

            UpdateInformationControlData(focusItem);

        }

 

        #endregion

        #region 추가 버튼 클릭시 처리하기 - addButton_Click(sender, e)

 

        /// <summary>

        /// 추가 버튼 클릭시 처리하기

        /// </summary>

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

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

        private void addButton_Click(object sender, EventArgs e)

        {

            SetEditMode(EditMode.Add);

 

            ClearInformationControlData();

 

            this.subjectTextEdit.Focus();

        }

 

        #endregion

        #region 수정 버튼 클릭시 처리하기 - updateButton_Click(sender, e)

 

        /// <summary>

        /// 수정 버튼 클릭시 처리하기

        /// </summary>

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

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

        private void updateButton_Click(object sender, EventArgs e)

        {

            SetEditMode(EditMode.Update);

 

            this.subjectTextEdit.Focus();

        }

 

        #endregion

        #region 삭제 버튼 클릭시 처리하기 - deleteButton_Click(sender, e)

 

        /// <summary>

        /// 삭제 버튼 클릭시 처리하기

        /// </summary>

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

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

        private void deleteButton_Click(object sender, EventArgs e)

        {

            TestModel focusItem = this.listGridView.GetFocusedRow() as TestModel;

 

            if(focusItem == null)

            {

                MessageBox.Show("삭제할 항목이 없습니다.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

 

                return;

            }

 

            if(MessageBox.Show("해당 항목을 삭제하시겠습니까?", "Confirmation", MessageBoxButtons.OKCancel,

                MessageBoxIcon.Question) == DialogResult.Cancel)

            {

                return ;

            }

 

            try

            {

                QueryHelper.DeleteItem(focusItem.ID);

 

                this.sourceList.Remove(focusItem);

 

                this.listGridView.RefreshData();

            }

            catch(Exception exception)

            {

                MessageBox.Show(exception.ToString());

            }

            finally

            {

                SetEditMode(EditMode.Normal);

 

                focusItem = this.listGridView.GetFocusedRow() as TestModel;

 

                UpdateInformationControlData(focusItem);

            }

        }

 

        #endregion

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

 

        /// <summary>

        /// 확인 버튼 클릭시 처리하기

        /// </summary>

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

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

        private void okButton_Click(object sender, EventArgs e)

        {

            if(this.editMode == EditMode.Add)

            {

                #region 편집 모드가 추가인 경우 처리한다.

 

                try

                {

                    TestModel inputItem = GetItemFromInformationControl();

 

                    inputItem.ID = Guid.NewGuid().ToString();

 

                    QueryHelper.InsertItem(inputItem);

 

                    TestModel newItem = QueryHelper.GetItem(inputItem.ID);

 

                    this.sourceList.Add(newItem);

 

                    this.listGridView.FocusedRowHandle = this.sourceList.Count - 1;

 

                    this.listGridView.RefreshData();

                }

                catch(Exception exception)

                {

                    MessageBox.Show(exception.ToString());

                }

                finally

                {

                    SetEditMode(EditMode.Normal);

 

                    TestModel focusItem = this.listGridView.GetFocusedRow() as TestModel;

 

                    UpdateInformationControlData(focusItem);

                }

 

                #endregion

            }

            else if(this.editMode == EditMode.Update)

            {

                #region 편집 모드가 수정인 경우 처리한다.

 

                TestModel focusItem = this.listGridView.GetFocusedRow() as TestModel;

                TestModel inputItem = GetItemFromInformationControl();

 

                try

                {

                    QueryHelper.UpdateItem(inputItem);

 

                    TestModel updateItem = QueryHelper.GetItem(inputItem.ID);

 

                    focusItem.Subject    = updateItem.Subject;

                    focusItem.UseYN      = updateItem.UseYN;

                    focusItem.UpdateDate = updateItem.UpdateDate;

 

                    this.listGridView.UpdateCurrentRow();

 

                    this.listGridView.RefreshData();

                }

                catch(Exception exception)

                {

                    MessageBox.Show(exception.ToString());

                }

                finally

                {

                    SetEditMode(EditMode.Normal);

 

                    UpdateInformationControlData(focusItem);

                }

 

                #endregion

            }

        }

 

        #endregion

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

 

        /// <summary>

        /// 취소 버튼 클릭시 처리하기

        /// </summary>

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

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

        private void cancelButton_Click(object sender, EventArgs e)

        {

            TestModel focusItem = this.listGridView.GetFocusedRow() as TestModel;

 

            UpdateInformationControlData(focusItem);

 

            SetEditMode(EditMode.Normal);

        }

 

        #endregion

 

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

 

        #region 편집 모드 설정하기 - SetEditMode(editMode)

        

        /// <summary>

        /// 편집 모드 설정하기

        /// </summary>

        /// <param name="editMode">편집 모드</param>

        private void SetEditMode(EditMode editMode)

        {

            this.editMode = editMode;

 

            switch(editMode)

            {

                case EditMode.Normal :

 

                    this.searchIDTextEdit.Properties.ReadOnly        = false;

                    this.searchSubjectTextEdit.Properties.ReadOnly   = false;

                    this.searchUseYNComboBoxEdit.Properties.ReadOnly = false;

                    this.searchCreateDateEdit1.Properties.ReadOnly   = false;

                    this.searchCreateDateEdit2.Properties.ReadOnly   = false;

 

                    this.searchButton.Enabled = true;

                    

                    this.idTextEdit.Properties.ReadOnly         = true;

                    this.subjectTextEdit.Properties.ReadOnly    = true;

                    this.useYNComboBoxEdit.Properties.ReadOnly  = true;

                    this.createDateTextEdit.Properties.ReadOnly = true;

                    this.updateDateTextEdit.Properties.ReadOnly = true;

 

                    this.addButton.Visible    = true;

                    this.updateButton.Visible = true;

                    this.deleteButton.Visible = true;

                    this.okButton.Visible     = false;

                    this.cancelButton.Visible = false;

 

                    break;

 

                case EditMode.Search:

                    

                    this.searchIDTextEdit.Properties.ReadOnly        = true;

                    this.searchSubjectTextEdit.Properties.ReadOnly   = true;

                    this.searchUseYNComboBoxEdit.Properties.ReadOnly = true;

                    this.searchCreateDateEdit1.Properties.ReadOnly   = true;

                    this.searchCreateDateEdit2.Properties.ReadOnly   = true;

                    

                    this.searchButton.Enabled = false;

 

                    this.idTextEdit.Properties.ReadOnly         = true;

                    this.subjectTextEdit.Properties.ReadOnly    = true;

                    this.useYNComboBoxEdit.Properties.ReadOnly  = true;

                    this.createDateTextEdit.Properties.ReadOnly = true;

                    this.updateDateTextEdit.Properties.ReadOnly = true;

 

                    this.addButton.Visible    = false;

                    this.updateButton.Visible = false;

                    this.deleteButton.Visible = false;

                    this.okButton.Visible     = false;

                    this.cancelButton.Visible = false;

 

                    break;

 

                case EditMode.Add:

 

                    this.searchIDTextEdit.Properties.ReadOnly        = true;

                    this.searchSubjectTextEdit.Properties.ReadOnly   = true;

                    this.searchUseYNComboBoxEdit.Properties.ReadOnly = true;

                    this.searchCreateDateEdit1.Properties.ReadOnly   = true;

                    this.searchCreateDateEdit2.Properties.ReadOnly   = true;

                    

                    this.searchButton.Enabled = true;

 

                    this.idTextEdit.Properties.ReadOnly         = true;

                    this.subjectTextEdit.Properties.ReadOnly    = false;

                    this.useYNComboBoxEdit.Properties.ReadOnly  = false;

                    this.createDateTextEdit.Properties.ReadOnly = true;

                    this.updateDateTextEdit.Properties.ReadOnly = true;

 

                    this.addButton.Visible    = false;

                    this.updateButton.Visible = false;

                    this.deleteButton.Visible = false;

                    this.okButton.Visible     = true;

                    this.cancelButton.Visible = true;

 

                    break;

 

                case EditMode.Update:

 

                    this.searchIDTextEdit.Properties.ReadOnly        = true;

                    this.searchSubjectTextEdit.Properties.ReadOnly   = true;

                    this.searchUseYNComboBoxEdit.Properties.ReadOnly = true;

                    this.searchCreateDateEdit1.Properties.ReadOnly   = true;

                    this.searchCreateDateEdit2.Properties.ReadOnly   = true;

                    

                    this.searchButton.Enabled = true;

 

                    this.idTextEdit.Properties.ReadOnly         = true;

                    this.subjectTextEdit.Properties.ReadOnly    = false;

                    this.useYNComboBoxEdit.Properties.ReadOnly  = false;

                    this.createDateTextEdit.Properties.ReadOnly = true;

                    this.updateDateTextEdit.Properties.ReadOnly = true;

 

                    this.addButton.Visible    = false;

                    this.updateButton.Visible = false;

                    this.deleteButton.Visible = false;

                    this.okButton.Visible     = true;

                    this.cancelButton.Visible = true;

 

                    break;

            }

        }

 

        #endregion

        #region 사용 여부 구하기 - GetUseYN(comboBoxEdit)

 

        /// <summary>

        /// 사용 여부 구하기

        /// </summary>

        /// <param name="comboBoxEdit">콤보 박스 에디터</param>

        /// <returns>사용 여부</returns>

        private string GetUseYN(ComboBoxEdit comboBoxEdit)

        {

            switch(comboBoxEdit.SelectedIndex)

            {

                case  0 : return string.Empty;

                case  1 : return "Y";

                case  2 : return "N";

                default : return string.Empty;

            }

        }

 

        #endregion

 

        #region 그리드 컬럼 구하기 - GetGridColumn(name, fieldName, caption, visible)

 

        /// <summary>

        /// 그리드 컬럼 구하기

        /// </summary>

        /// <param name="name">명칭</param>

        /// <param name="caption">제목</param>

        /// <param name="fieldName">필드명</param>

        /// <param name="visible">표시 여부</param>

        /// <returns>그리드 컬럼</returns>

        private GridColumn GetGridColumn(string name, string fieldName, string caption, int width, bool visible)

        {

            GridColumn gridColumn = new GridColumn();

 

            gridColumn.Name      = name;

            gridColumn.FieldName = fieldName;

            gridColumn.Caption   = caption;

            gridColumn.Width     = width;

            gridColumn.Visible   = visible;

 

            gridColumn.AppearanceHeader.Options.UseTextOptions = true;

            gridColumn.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            gridColumn.AppearanceHeader.TextOptions.VAlignment = VertAlignment.Center;

 

            return gridColumn;

        }

 

        #endregion

        #region 리스트 그리드 컨트롤 데이터 설정하기 - SetGridControlData(sourceList)

 

        /// <summary>

        /// 리스트 그리드 컨트롤 데이터 설정하기

        /// </summary>

        /// <param name="sourceList">소스 리스트</param>

        private void SetListGridControlData(List<TestModel> sourceList)

        {

            this.listGridControl.DataSource = null;

 

            if(this.sourceList != null)

            {

                this.sourceList.Clear();

 

                this.sourceList = null;

            }

 

            this.sourceList = sourceList;

 

            this.listGridControl.DataSource = this.sourceList;

 

            this.listGridControl.RefreshDataSource();

 

            this.listGridView.BestFitColumns();

        }

 

        #endregion

 

        #region 정보 컨트롤 데이터 지우기 - ClearInformationControlData()

 

        /// <summary>

        /// 정보 컨트롤 데이터 지우기

        /// </summary>

        private void ClearInformationControlData()

        {

            this.idTextEdit.Text         = null;

            this.subjectTextEdit.Text    = null;

            this.useYNComboBoxEdit.Text  = null;

            this.createDateTextEdit.Text = null;

            this.updateDateTextEdit.Text = null;

        }

 

        #endregion

        #region 정보 컨트롤 데이터 설정하기 - SetInformationControlData(source)

 

        /// <summary>

        /// 정보 컨트롤 데이터 설정하기

        /// </summary>

        /// <param name="source">소스</param>

        private void SetInformationControlData(TestModel source)

        {

            this.idTextEdit.Text      = source.ID;

            this.subjectTextEdit.Text = source.Subject;

 

            if(source.UseYN == "Y")

            {

                this.useYNComboBoxEdit.SelectedIndex = 1;

            }

            else if(source.UseYN == "N")

            {

                this.useYNComboBoxEdit.SelectedIndex = 2;

            }

            else

            {

                this.useYNComboBoxEdit.SelectedIndex = 0;

            }

 

            this.createDateTextEdit.Text = source.CreateDate.ToString("yyyy-MM-dd HH:mm:ss");

            this.updateDateTextEdit.Text = source.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss");

        }

 

        #endregion

        #region 정보 컨트롤 데이터 업데이트 하기 - UpdateInformationControlData(source)

 

        /// <summary>

        /// 정보 컨트롤 데이터 업데이트 하기

        /// </summary>

        /// <param name="source">소스</param>

        private void UpdateInformationControlData(TestModel source)

        {

            if(source == null)

            {

                ClearInformationControlData();

            }

            else

            {

                SetInformationControlData(source);

            }

        }

 

        #endregion

        #region 정보 컨트롤에서 항목 구하기 - GetItemFromInformationControl()

 

        /// <summary>

        /// 정보 컨트롤에서 항목 구하기

        /// </summary>

        /// <returns>항목</returns>

        private TestModel GetItemFromInformationControl()

        {

            TestModel test = new TestModel();

 

            test.ID      = this.idTextEdit.Text.Trim();

            test.Subject = this.subjectTextEdit.Text.Trim();

 

            switch(useYNComboBoxEdit.SelectedIndex)

            {

                case 1  : test.UseYN = "Y";  break;

                case 2  : test.UseYN = "N";  break;

                default : test.UseYN = null; break;

            }

            

            test.CreateDate = DateTime.Now;

            test.UpdateDate = DateTime.Now;

 

            return test;

        }

 

        #endregion

    }

}

 

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

Posted by 사용자 icodebroker