블로그 이미지
따시쿵

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. 5. 7. 11:22 C# with ListView

프로그램 설명


페이지 나누기가 있는 ListView 예제입니다.

기본적인 아이디어는 Listview Paging in C# 에 있는 자료를 가져다가 사용했으며, 몇가지 성능을 위해서 수정한 부분이 있습니다.


수정한 부분


1. 데이타 쿼리는 폼이 로드될 시에 전체적으로 한번만 데이타베이스에서 가져오고 그 다음 페이지 이동시에는 처음 로드한 데이타셋에서 자료를 가져옵니다.


2. 하단에 있는 처음으로, 이전으로, 다음으로, 마지막으로 버튼 이벤트를 한 곳으로 모아서 처리했습니다.


3. 컬럼 이벤트를 주어서 sorting 기능도 추가했습니다. (ascending, descending)


실행 후



프로그램 작성 순서


1. 페이지 나누기 기본 알고리즘

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
31
32
33
34
35
36
37
static void Main(string[] args)
{
    int TotalRec, NRPP;
    double TotalPages = 0;
    String p;
    System.Console.WriteLine("Enter Total Records");
    TotalRec = Convert.ToInt32(System.Console.ReadLine());
    //Getting value to set number records are shown in the page.
    System.Console.WriteLine("Enter No. of Records Per Page");
    NRPP = Convert.ToInt32(System.Console.ReadLine());
    //calculating Total Pages
    TotalPages = Math.Ceiling( Convert.ToDouble(TotalRec) / NRPP);
 
    System.Console.WriteLine("The Total Pages:{0}", TotalPages);
    //Creating Page Indexes
    int i, j;
    for (int k = 1; k <= TotalPages; k++)
    {
        System.Console.WriteLine("\n\n Page No:{0} \n", k);
        i = (k - 1) * NRPP;
        int start = i;
        int end = 0;
        j = k * NRPP;
        for (; i < j; i++)
        {
            if (i >= TotalRec)
            {
                break;
            }
            System.Console.WriteLine("Record Index:{0}", i);
            end = i;
        }
        System.Console.WriteLine("Records Showing From {0} to {1}", (start + 1), (end + 1));
        System.Console.WriteLine("*****End of Page***** \n");
        p = System.Console.ReadLine();
    }
}


2. 전역 변수들

1
2
3
4
5
6
7
8
9
10
11
public class LsvPageGlobVar
{
    public static string ConStr;
    public static DataTable sqlDataTable = new DataTable();
    public static int TotalRec;         //Variable for getting Total Records of the Table
    public static int NRPP;             //Variable for Setting the Number of Recrods per listiview page
    public static int Page;             //List View Page for Navigate or move
    public static double TotalPages;    //Varibale for Counting Total Pages.
    public static int RecStart;         //Variable for Getting Every Page Starting Record Index
    public static int RecEnd;           //Variable for Getting Every Page End Record Index
}


3. 페이지별로 데이타 가져오는 method

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class LsvPageFunc
{
    public static void FillLsvData(BindingList<contacts> sqlData, ListView lvList, int imageID)
    {
        lvList.Items.Clear();
         
        // total record count
        LsvPageGlobVar.TotalRec = sqlData.Count;
 
        // calculate total page count
        LsvPageGlobVar.TotalPages = Math.Ceiling(Convert.ToDouble(LsvPageGlobVar.TotalRec) / LsvPageGlobVar.NRPP);
      
 
        //for adding records to the listview from datatable
        int l, k;
 
        l = (LsvPageGlobVar.Page - 1) * LsvPageGlobVar.NRPP;
        k = ((LsvPageGlobVar.Page) * LsvPageGlobVar.NRPP);
 
        LsvPageGlobVar.RecStart = l + 1;
        if (k > LsvPageGlobVar.TotalRec)
        {
            LsvPageGlobVar.RecEnd = LsvPageGlobVar.TotalRec;
        }
        else
        {
            LsvPageGlobVar.RecEnd = k;
        }
 
        int index = 0;
        for (; l < k; l++)
        {
            if (l >= LsvPageGlobVar.TotalRec)
            {
                break;
            }
 
            // Not display image
            //ListViewItem item = new ListViewItem();
            //item.Text = sqlData[l].Idx.ToString();
            //item.SubItems.Add(sqlData[l].Name);
            //item.SubItems.Add(sqlData[l].BirthInfo);
            //item.SubItems.Add(sqlData[l].ZipCode);
            //item.SubItems.Add(sqlData[l].Address);
            //item.SubItems.Add(sqlData[l].HomeTelephone);
            //item.SubItems.Add(sqlData[l].CompanyTelephone);
            //item.SubItems.Add(sqlData[l].Mobile);
            //item.SubItems.Add(sqlData[l].Company);
            //item.SubItems.Add(sqlData[l].RegDate);
            //lvList.Items.Add(item);
 
            // Display image
            lvList.Items.Add(sqlData[l].Idx.ToString(), imageID);
            lvList.Items[index].SubItems.Add(sqlData[l].Name);
            lvList.Items[index].SubItems.Add(sqlData[l].BirthInfo);
            lvList.Items[index].SubItems.Add(sqlData[l].ZipCode);
            lvList.Items[index].SubItems.Add(sqlData[l].Address);
            lvList.Items[index].SubItems.Add(sqlData[l].HomeTelephone);
            lvList.Items[index].SubItems.Add(sqlData[l].CompanyTelephone);
            lvList.Items[index].SubItems.Add(sqlData[l].Mobile);
            lvList.Items[index].SubItems.Add(sqlData[l].Company);
            lvList.Items[index].SubItems.Add(sqlData[l].RegDate);
 
            index++;
        }
    }
}


4. 실제적으로 페이지별로 데이타 호출하는 방법

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
31
32
33
34
35
36
37
38
39
40
41
42
43
Button button = (Button)sender;
 
switch(button.Name)
{
    case "btnFirst":
        {
            LsvPageGlobVar.Page = 1;
            LsvPageFunc.FillLsvData(ContactList, lsvData, 0);
            lblInfo.Text = "Record Shown: " + LsvPageGlobVar.RecStart + " to " + LsvPageGlobVar.RecEnd + "                      Page " + LsvPageGlobVar.Page + " of " + LsvPageGlobVar.TotalPages;
 
            break;
        }
    case "btnPrev":
        {
            if (LsvPageGlobVar.Page > 1)
            {
                LsvPageGlobVar.Page--;
            }
            LsvPageFunc.FillLsvData(ContactList, lsvData, 1);
            lblInfo.Text = "Record Shown: " + LsvPageGlobVar.RecStart + " to " + LsvPageGlobVar.RecEnd + "                      Page " + LsvPageGlobVar.Page + " of " + LsvPageGlobVar.TotalPages;
 
            break;
        }
    case "btnNext":
        {
            if (LsvPageGlobVar.Page < LsvPageGlobVar.TotalPages)
            {
                LsvPageGlobVar.Page++;
            }
            LsvPageFunc.FillLsvData(ContactList, lsvData, 2);
            lblInfo.Text = "Record Shown: " + LsvPageGlobVar.RecStart + " to " + LsvPageGlobVar.RecEnd + "                      Page " + LsvPageGlobVar.Page + " of " + LsvPageGlobVar.TotalPages;
 
            break;
        }
    case "btnLast":
        {
            LsvPageGlobVar.Page = Convert.ToInt32(LsvPageGlobVar.TotalPages);
            LsvPageFunc.FillLsvData(ContactList, lsvData, 3);
            lblInfo.Text = "Record Shown: " + LsvPageGlobVar.RecStart + " to " + LsvPageGlobVar.RecEnd + "                      Page " + LsvPageGlobVar.Page + " of " + LsvPageGlobVar.TotalPages;
 
            break;
        }
}


소스 파일 :

ListViewExample5.zip


posted by 따시쿵
2015. 4. 30. 15:53 C# with ListView

프로그램 설명


ListView 은 sorting 기능을 items 에서 지원하므로, 수작업으로 sub-items 까지 sorting 하는 기능을 작성해야 합니다. 그래서 필수적인 IComparer 인터페이스를 이용해서 구현합니다. 


예제에 있는 sorting 타입은 3가지 타입으로 숫자, 날짜, 문자열로 나뉘어 구분합니다.


실행 후


프로그램 작성 순서


1. IComparer 에서 상속받은 ListViewComparer class

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
using System.Windows.Forms;
 
namespace SortListViewColumn.lib
{
    // Compares two ListView items based on a selected column.
    public class ListViewComparer : System.Collections.IComparer
    {
        private int ColumnNumber;
        private SortOrder SortOrder;
 
        public ListViewComparer(int column_number, SortOrder sort_order)
        {
            ColumnNumber = column_number;
            SortOrder = sort_order;
        }
 
        // Compare two ListViewItems.
        public int Compare(object object_x, object object_y)
        {
            // Get the objects as ListViewItems.
            ListViewItem item_x = object_x as ListViewItem;
            ListViewItem item_y = object_y as ListViewItem;
 
            // Get the corresponding sub-item values.
            string string_x;
            if (item_x.SubItems.Count <= ColumnNumber)
            {
                string_x = "";
            }
            else
            {
                string_x = item_x.SubItems[ColumnNumber].Text;
            }
 
            string string_y;
            if (item_y.SubItems.Count <= ColumnNumber)
            {
                string_y = "";
            }
            else
            {
                string_y = item_y.SubItems[ColumnNumber].Text;
            }
 
            // Compare them.
            int result;
            double double_x, double_y;
            if (double.TryParse(string_x, out double_x) &&
                double.TryParse(string_y, out double_y))
            {
                // Treat as a number.
                result = double_x.CompareTo(double_y);
            }
            else
            {
                DateTime date_x, date_y;
                if (DateTime.TryParse(string_x, out date_x) &&
                    DateTime.TryParse(string_y, out date_y))
                {
                    // Treat as a date.
                    result = date_x.CompareTo(date_y);
                }
                else
                {
                    // Treat as a string.
                    result = string_x.CompareTo(string_y);
                }
            }
 
            // Return the correct result depending on whether
            // we're sorting ascending or descending.
            if (SortOrder == SortOrder.Ascending)
            {
                return result;
            }
            else
            {
                return -result;
            }
        }
    }
}


2. ColumnClick 이벤트 method

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
{
    // Get the new sorting column.
    ColumnHeader new_sorting_column = listView1.Columns[e.Column];
 
    // Figure out the new sorting order.
    System.Windows.Forms.SortOrder sort_order;
    if (SortingColumn == null)
    {
        // New column. Sort ascending.
        sort_order = SortOrder.Ascending;
    }
    else
    {
        // See if this is the same column.
        if (new_sorting_column == SortingColumn)
        {
            // Same column. Switch the sort order.
            if (SortingColumn.Text.StartsWith("> "))
            {
                sort_order = SortOrder.Descending;
            }
            else
            {
                sort_order = SortOrder.Ascending;
            }
        }
        else
        {
            // New column. Sort ascending.
            sort_order = SortOrder.Ascending;
        }
 
        // Remove the old sort indicator.
        SortingColumn.Text = SortingColumn.Text.Substring(2);
    }
 
    // Display the new sort order.
    SortingColumn = new_sorting_column;
    if (sort_order == SortOrder.Ascending)
    {
        SortingColumn.Text = "> " + SortingColumn.Text;
    }
    else
    {
        SortingColumn.Text = "< " + SortingColumn.Text;
    }
 
    // Create a comparer.
    listView1.ListViewItemSorter = new ListViewComparer(e.Column, sort_order);
 
    // Sort.
    listView1.Sort();
 
    // Display order column and sorting type
    toolStripStatusLabel1.Text = "Sorting : " + SortingColumn.Text;
}


소스 파일 : 

ListViewExample2.zip

posted by 따시쿵
2015. 4. 28. 15:18 C# with ListView

프로그램 설명


ListView 를 이용한 데이타베이스 연산 예제입니다.


데이타베이스 테이블은 아래와 같습니다.


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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
CREATE TABLE [dbo].[tbl_contacts](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NOT NULL,
    [BirthInfo] [char](8) NOT NULL,
    [ZipCode] [char](7) NOT NULL,
    [Address] [varchar](300) NOT NULL,
    [HomeTelephone] [varchar](50) NOT NULL,
    [CompanyTelephone] [varchar](50) NOT NULL,
    [Mobile] [varchar](50) NOT NULL,
    [Company] [varchar](50) NOT NULL,
    [RegDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_contacts] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
 
GO
 
SET ANSI_PADDING OFF
GO
 
ALTER TABLE [dbo].[tbl_contacts] ADD  DEFAULT ('') FOR [Name]
GO
 
ALTER TABLE [dbo].[tbl_contacts] ADD  DEFAULT ('') FOR [BirthInfo]
GO
 
ALTER TABLE [dbo].[tbl_contacts] ADD  DEFAULT ('') FOR [ZipCode]
GO
 
ALTER TABLE [dbo].[tbl_contacts] ADD  DEFAULT ('') FOR [Address]
GO
 
ALTER TABLE [dbo].[tbl_contacts] ADD  DEFAULT ('') FOR [HomeTelephone]
GO
 
ALTER TABLE [dbo].[tbl_contacts] ADD  DEFAULT ('') FOR [CompanyTelephone]
GO
 
ALTER TABLE [dbo].[tbl_contacts] ADD  DEFAULT ('') FOR [Mobile]
GO
 
ALTER TABLE [dbo].[tbl_contacts] ADD  DEFAULT ('') FOR [Company]
GO
 
ALTER TABLE [dbo].[tbl_contacts] ADD  DEFAULT (getdate()) FOR [RegDate]
GO


실행 후


프로그램 작성 순서


데이타베이스에서 ListView 에 데이타 보여주기


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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]");
 
listView1.Items.Clear();
 
if (dt.Rows.Count > 0)
{
    foreach (DataRow dr in dt.Rows)
    {
        ListViewItem item = new ListViewItem();
        item.Text = dr[0].ToString();
        for (int i = 1; i < dt.Columns.Count; i++)
        {
            item.SubItems.Add(dr[i].ToString());
        }
        listView1.Items.Add(item);
    }
}
 
dt.Dispose();
sdo.Dispose();


소스 파일 : 

ListViewExample1.zip


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

페이지 나누기가 있는 ListView  (0) 2015.05.07
Column Sorting 이 있는 ListView  (0) 2015.04.30
posted by 따시쿵