블로그 이미지
따시쿵

calendar

1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

Notice

2015. 4. 27. 16:29 C# with DataGridView

프로그램 설명


DataGridView 칼럼을 sorting 하는 예제입니다.

SortableBindingList class 를 이용하며 BindingList class 에서 상속받은 것이며, PropertyComparer class 는 IComparer class 를 상속하여 구현하였습니다.


실행 후


1. 정렬을 하지 않은 경우


2. 정렬을 한 경우


프로그램 작성 순서


1. 라이브러리 클래스


SortableBindingList.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using Be.Timvw.Framework.Collections.Generic;

namespace Be.Timvw.Framework.ComponentModel
{
    public class SortableBindingList<t> : BindingList<t>
    {
        private readonly Dictionary<type, propertycomparer<t>> comparers;
        private bool isSorted;
        private ListSortDirection listSortDirection;
        private PropertyDescriptor propertyDescriptor;

        public SortableBindingList()
            : base(new List<t>())
        {
            this.comparers = new Dictionary<type, propertycomparer<t>>();
        }

        public SortableBindingList(IEnumerable<t> enumeration)
            : base(new List<t>(enumeration))
        {
            this.comparers = new Dictionary<type, propertycomparer<t>>();
        }

        protected override bool SupportsSortingCore
        {
            get { return true; }
        }

        protected override bool IsSortedCore
        {
            get { return this.isSorted; }
        }

        protected override PropertyDescriptor SortPropertyCore
        {
            get { return this.propertyDescriptor; }
        }

        protected override ListSortDirection SortDirectionCore
        {
            get { return this.listSortDirection; }
        }

        protected override bool SupportsSearchingCore
        {
            get { return true; }
        }

        protected override void ApplySortCore(PropertyDescriptor property, ListSortDirection direction)
        {
            List<t> itemsList = (List<t>)this.Items;

            Type propertyType = property.PropertyType;
            PropertyComparer<t> comparer;
            if (!this.comparers.TryGetValue(propertyType, out comparer))
            {
                comparer = new PropertyComparer<t>(property, direction);
                this.comparers.Add(propertyType, comparer);
            }

            comparer.SetPropertyAndDirection(property, direction);
            itemsList.Sort(comparer);

            this.propertyDescriptor = property;
            this.listSortDirection = direction;
            this.isSorted = true;

            this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
        }

        protected override void RemoveSortCore()
        {
            this.isSorted = false;
            this.propertyDescriptor = base.SortPropertyCore;
            this.listSortDirection = base.SortDirectionCore;

            this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
        }

        protected override int FindCore(PropertyDescriptor property, object key)
        {
            int count = this.Count;
            for (int i = 0; i < count; ++i)
            {
                T element = this[i];
                if (property.GetValue(element).Equals(key))
                {
                    return i;
                }
            }

            return -1;
        }
    }
}


PropertyComparer.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

namespace Be.Timvw.Framework.Collections.Generic
{
    public class PropertyComparer<t> : IComparer<t>
    {
        private readonly IComparer comparer;
        private PropertyDescriptor propertyDescriptor;
        private int reverse;

        public PropertyComparer(PropertyDescriptor property, ListSortDirection direction)
        {
            this.propertyDescriptor = property;
            Type comparerForPropertyType = typeof(Comparer<>).MakeGenericType(property.PropertyType);
            this.comparer = (IComparer)comparerForPropertyType.InvokeMember("Default", BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.Public, null, null, null);
            this.SetListSortDirection(direction);
        }

        #region IComparer<t> Members

        public int Compare(T x, T y)
        {
            return this.reverse * this.comparer.Compare(this.propertyDescriptor.GetValue(x), this.propertyDescriptor.GetValue(y));
        }

        #endregion

        private void SetPropertyDescriptor(PropertyDescriptor descriptor)
        {
            this.propertyDescriptor = descriptor;
        }

        private void SetListSortDirection(ListSortDirection direction)
        {
            this.reverse = direction == ListSortDirection.Ascending ? 1 : -1;
        }

        public void SetPropertyAndDirection(PropertyDescriptor descriptor, ListSortDirection direction)
        {
            this.SetPropertyDescriptor(descriptor);
            this.SetListSortDirection(direction);
        }
    }
}


2. 사용하는 방법

        private void RebindGridForPageChange()
        {
            //Rebinding the Datagridview with data
            int datasourcestartIndex = (CurrentPage - 1) * PageRows;
            Templist = new List<contacts>();
            for (int i = datasourcestartIndex; i < datasourcestartIndex + PageRows; i++)
            {
                if (i >= Baselist.Count)
                    break;

                Templist.Add(Baselist[i]);
            }

            //Set List data to SortableBindingList 
            SortableBindingList<contacts> plist = new SortableBindingList<contacts>(Templist);

            dataGridView1.DataSource = plist;
            dataGridView1.Refresh();
        }


소스 파일 : 

DataGridViewExample3.zip

posted by 따시쿵
2015. 4. 24. 16:11 C# with DataGridView
프로그램 설명

한 화면에 20개의 데이타를 보여주고, 페이지 번호가 있어서 각 페이지로 바로 이동 할 수 있는 예제입니다. 데이타는 데이타베이스에 10,000 개의 데이타를 임의로 입력하고 쿼리를 통해서 가져오는 방법입니다.

전체적인 로직은 System.ComponentModel.BindingList 를 이용해서, 전체 데이타를 가져오고 난 후에 각 페이지로 이동 할 때에 전체 데이타에서 해당하는 데이타 20개씩을 화면에 보여줍니다.

데이타베이스 화면



실행 화면


1. 첫화면 로딩이 마친 후



2. 페이지 이동을 13 페이지로 한 후



프로그램 작성


소스 파일안에 주석을 달아 놓았으니 확인 해 보시면 됩니다.

    public partial class MainForm : Form
    {
        #region Initialize fields
        private int CurrentPage = 1;
        int PagesCount = 1;
        int PageRows = 20;

        BindingList<contacts> Baselist = null;
        BindingList<contacts> Templist = null;
        #endregion

        #region InitialIze MainForm()
        public MainForm()
        {
            InitializeComponent();
        }

        /// 
        /// Call MainForm
        /// 
        /// 
        /// 
        private void MainForm_Load(object sender, EventArgs e)
        {
            Baselist = FillDataforGrid();
            PagesCount = Convert.ToInt32(Math.Ceiling(Baselist.Count * 1.0 / PageRows));
            
            DataGridViewHeaderSetting();

            CurrentPage = 1;
            RefreshPagination();
            RebindGridForPageChange();
        }

        /// 
        /// Get all contacts database data
        /// 
        /// 
        private BindingList<contacts> FillDataforGrid()
        {
            SQLOperator sdo = new SQLOperator("SampleDBConnectionString");
            DataTable dt = sdo.ExecuteQuery(@"select Id, Name, BirthInfo, ZipCode, [Address], HomeTelephone, 
                                                     CompanyTelephone, Mobile, Company, convert(char(10), RegDate, 120) as RegDate
                                              from [dbo].[tbl_contacts]");

            BindingList<contacts> pContact = new BindingList<contacts>();

            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    pContact.Add(new Contacts()
                    {
                        Idx = Convert.ToInt32(row["Id"]),
                        Name = row["Name"].ToString(),
                        BirthInfo = row["BirthInfo"].ToString(),
                        ZipCode = row["ZipCode"].ToString(),
                        Address = row["Address"].ToString(),
                        HomeTelephone = row["HomeTelephone"].ToString(),
                        CompanyTelephone = row["CompanyTelephone"].ToString(),
                        Mobile = row["Mobile"].ToString(),
                        Company = row["Company"].ToString(),
                        RegDate = row["RegDate"].ToString()
                    });
                }
            }

            return pContact;
        }

        #endregion

        #region Button Events
        /// 
        /// Exit button
        /// 
        /// 
        /// 
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(MessageBox.Show(Properties.Resources.TerminateConfirmMsg, "확인", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes )
                this.Close();
        }

        /// 
        /// ToolstripButton(처음으로, 앞으로, 1, 2, 3, 4, 5, 뒤로, 마지막으로)
        /// 
        /// 
        /// 
        private void ToolStripButtonClick(object sender, EventArgs e)
        {
            try
            {
                ToolStripButton ToolStripButton = ((ToolStripButton)sender);

                //Determining the current page
                if (ToolStripButton == btnBackward)
                    CurrentPage--;
                else if (ToolStripButton == btnForward)
                    CurrentPage++;
                else if (ToolStripButton == btnLast)
                    CurrentPage = PagesCount;
                else if (ToolStripButton == btnFirst)
                    CurrentPage = 1;
                else
                    CurrentPage = Convert.ToInt32(ToolStripButton.Text, CultureInfo.InvariantCulture);

                if (CurrentPage < 1)
                    CurrentPage = 1;
                else if (CurrentPage > PagesCount)
                    CurrentPage = PagesCount;

                //Rebind the Datagridview with the data.
                RebindGridForPageChange();

                //Change the pagiantions buttons according to page number
                RefreshPagination();
            }
            catch (Exception) { }
        }
        #endregion

        #region Page setting
        private void RefreshPagination()
        {
            ToolStripButton[] items = new ToolStripButton[] { toolStripButton1, toolStripButton2, toolStripButton3, toolStripButton4, toolStripButton5 };

            //pageStartIndex contains the first button number of pagination.
            int pageStartIndex = 1;

            if (PagesCount > 5 && CurrentPage > 2)
                pageStartIndex = CurrentPage - 2;

            if (PagesCount > 5 && CurrentPage > PagesCount - 2)
                pageStartIndex = PagesCount - 4;

            for (int i = pageStartIndex; i < pageStartIndex + 5; i++)
            {
                if (i > PagesCount)
                {
                    items[i - pageStartIndex].Visible = false;
                }
                else
                {
                    //Changing the page numbers
                    items[i - pageStartIndex].Text = i.ToString(CultureInfo.InvariantCulture);

                    //Setting the Appearance of the page number buttons
                    if (i == CurrentPage)
                    {
                        items[i - pageStartIndex].BackColor = Color.Black;
                        items[i - pageStartIndex].ForeColor = Color.White;
                    }
                    else
                    {
                        items[i - pageStartIndex].BackColor = Color.White;
                        items[i - pageStartIndex].ForeColor = Color.Black;
                    }
                }
            }

            //Enabling or Disalbing pagination first, last, previous , next buttons
            if (CurrentPage == 1)
                btnBackward.Enabled = btnFirst.Enabled = false;
            else
                btnBackward.Enabled = btnFirst.Enabled = true;

            if (CurrentPage == PagesCount)
                btnForward.Enabled = btnLast.Enabled = false;

            else
                btnForward.Enabled = btnLast.Enabled = true;
        }
        #endregion

        #region Get data in current page
        private void RebindGridForPageChange()
        {
            //Rebinding the Datagridview with data
            int datasourcestartIndex = (CurrentPage - 1) * PageRows;
            Templist = new BindingList<contacts>();
            for (int i = datasourcestartIndex; i < datasourcestartIndex + PageRows; i++)
            {
                if (i >= Baselist.Count)
                    break;

                Templist.Add(Baselist[i]);
            }

            dataGridView1.DataSource = Templist;
            dataGridView1.Refresh();
        }
        #endregion

        #region DataGridView Header Setting
        /// 
        /// Set DataGridView header text and property(text align, font size)
        /// 
        private void DataGridViewHeaderSetting()
        {
            dataGridView1.AutoGenerateColumns = false;
            

            DataGridViewTextBoxColumn IdxColumn = new DataGridViewTextBoxColumn();
            IdxColumn.DataPropertyName = "Idx";
            IdxColumn.HeaderText = "No.";

            DataGridViewTextBoxColumn NameColumn = new DataGridViewTextBoxColumn();
            NameColumn.DataPropertyName = "Name";
            NameColumn.HeaderText = "이름";

            DataGridViewTextBoxColumn BirthInfoColumn = new DataGridViewTextBoxColumn();
            BirthInfoColumn.DataPropertyName = "BirthInfo";
            BirthInfoColumn.HeaderText = "생년월일";

            DataGridViewTextBoxColumn ZipCodeColumn = new DataGridViewTextBoxColumn();
            ZipCodeColumn.DataPropertyName = "ZipCode";
            ZipCodeColumn.HeaderText = "우편번호";

            DataGridViewTextBoxColumn AddressColumn = new DataGridViewTextBoxColumn();
            AddressColumn.DataPropertyName = "Address";
            AddressColumn.HeaderText = "주 소";

            DataGridViewTextBoxColumn HomeTelephoneColumn = new DataGridViewTextBoxColumn();
            HomeTelephoneColumn.DataPropertyName = "HomeTelephone";
            HomeTelephoneColumn.HeaderText = "집 전화번호";

            DataGridViewTextBoxColumn CompanyTelephoneColumn = new DataGridViewTextBoxColumn();
            CompanyTelephoneColumn.DataPropertyName = "CompanyTelephone";
            CompanyTelephoneColumn.HeaderText = "회사 전화번호";

            DataGridViewTextBoxColumn MobileColumn = new DataGridViewTextBoxColumn();
            MobileColumn.DataPropertyName = "Mobile";
            MobileColumn.HeaderText = "핸드폰번호";

            DataGridViewTextBoxColumn CompanyColumn = new DataGridViewTextBoxColumn();
            CompanyColumn.DataPropertyName = "Company";
            CompanyColumn.HeaderText = "회사명";

            DataGridViewTextBoxColumn RegDateColumn = new DataGridViewTextBoxColumn();
            RegDateColumn.DataPropertyName = "RegDate";
            RegDateColumn.HeaderText = "등록일";

            dataGridView1.Columns.Add(IdxColumn);
            dataGridView1.Columns.Add(NameColumn);
            dataGridView1.Columns.Add(BirthInfoColumn);
            dataGridView1.Columns.Add(ZipCodeColumn);
            dataGridView1.Columns.Add(AddressColumn);
            dataGridView1.Columns.Add(HomeTelephoneColumn);
            dataGridView1.Columns.Add(CompanyTelephoneColumn);
            dataGridView1.Columns.Add(MobileColumn);
            dataGridView1.Columns.Add(CompanyColumn);
            dataGridView1.Columns.Add(RegDateColumn);

            foreach (DataGridViewColumn col in dataGridView1.Columns)
            {
                col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                col.HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Bold, GraphicsUnit.Pixel);
                col.HeaderCell.Style.ForeColor = Color.White;

                // Set the column size automatically
                col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            }

            // Set the header column BackColor
            dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.DarkOrange;
            dataGridView1.EnableHeadersVisualStyles = false;
        }
        #endregion
    }


소스 파일 :

DataGridViewExample2.zip


posted by 따시쿵
2015. 4. 22. 17:08 C# with DataGridView

프로그램 설명


DataGridView 의 datasource 와 List class를 이용하는 방법입니다.

데이타베이스 4칙 연산을 수행합니다.


Contacts class 는 아래와 같습니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Windows.Forms;
using DataGridViewExample.lib;


namespace DataGridViewExample.data
{
    public class Contacts
    {
        #region Properties
        public int Idx { get; set; }
        public string Name { get; set; }
        public string BirthInfo { get; set; }
        public string ZipCode { get; set; }
        #endregion

        #region Functions
        /// 
        // Add the contacts info
        /// 
        /// 
        public bool AddContacts()
        {
            bool retval = false;
            try
            { 
                SQLOperator sdo = new SQLOperator("SampleDBConnectionString");

                string query = @"insert into [dbo].[tbl_contacts](Name, BirthInfo, ZipCode)
                                    values(@Name, @BirthInfo, @ZipCode);";

                sdo.ExecuteNoneQuery(query,
                                    new SqlParameter[]
                                    {
                                        new SqlParameter("@Name", Name),
                                        new SqlParameter("@BirthInfo", BirthInfo),
                                        new SqlParameter("@ZipCode", ZipCode)
                                    },
                                    CommandType.Text);
                sdo.Dispose();

                retval = true;
            }
            catch (SqlException se)
            {
                Trace.WriteLine(se.Message);
                retval = false;
            }
            catch(Exception ex)
            {
                Trace.WriteLine(ex.Message);
                retval = false;
            }

            return retval;
        }

        /// 
        /// Modify the contacts info
        /// 
        /// 
        public bool ModifyContacts()
        {
            bool retval = false;
            try
            {
                SQLOperator sdo = new SQLOperator("SampleDBConnectionString");

                string query = @"update [dbo].[tbl_contacts]
                                set  Name = @Name, BirthInfo = @BirthInfo, ZipCode = @ZipCode
                                where Id = @Idx;";

                sdo.ExecuteNoneQuery(query,
                                    new SqlParameter[]
                                    {
                                        new SqlParameter("@Name", Name),
                                        new SqlParameter("@BirthInfo", BirthInfo),
                                        new SqlParameter("@ZipCode", ZipCode),
                                        new SqlParameter("@Idx", Idx)
                                    },
                                    CommandType.Text);
                sdo.Dispose();

                retval = true;
            }
            catch (SqlException se)
            {
                Trace.WriteLine(se.Message);
                retval = false;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
                retval = false;
            }

            return retval;
        }

        public bool RemoveContacts()
        {
            bool retval = false;
            try
            {
                SQLOperator sdo = new SQLOperator("SampleDBConnectionString");

                string query = @"delete from [dbo].[tbl_contacts]
                                where Id = @Idx;";

                sdo.ExecuteNoneQuery(query,
                                    new SqlParameter[]
                                    {
                                        new SqlParameter("@Idx", Idx)
                                    },
                                    CommandType.Text);
                sdo.Dispose();

                retval = true;
            }
            catch (SqlException se)
            {
                Trace.WriteLine(se.Message);
                retval = false;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
                retval = false;
            }

            return retval;
        }
        #endregion
    }
}


실행 화면



소스 파일 

DataGridViewExample.zip


'C# with DataGridView' 카테고리의 다른 글

Column Sorting 이 있는 DataGridView  (0) 2015.04.27
페이지 나누기가 있는 DataGridView  (0) 2015.04.24
posted by 따시쿵
prev 1 next