VB.NET/C# DataTable 여러 컬럼 정렬하기, Multiple Column Sort

2020. 6. 2. 13:38VB.NET

728x90
반응형

 

임시 테이블 구성

C# Code

public Form1()
{
    InitializeComponent();

    DataTable dt_temp = new DataTable();
    dt_temp.Columns.Add("ID");
    dt_temp.Columns.Add("일자");
    dt_temp.Columns.Add("동");
    dt_temp.Columns.Add("호");

    dt_temp.Rows.Add(1, "2020-04-13", "2101", "101");
    dt_temp.Rows.Add(2, "2020-05-20", "2101", "1301");
    dt_temp.Rows.Add(3, "2020-04-13", "2101", "1302");
    dt_temp.Rows.Add(4, "2020-05-22", "2101", "2002");
    dt_temp.Rows.Add(5, "2020-12-11", "2101", "201");
    dt_temp.Rows.Add(6, "2020-12-11", "2101", "801");
    dt_temp.Rows.Add(7, "2020-12-11", "2101", "801");

    DataGridView1.DataSource = dt_temp;
}

 

VB.NET Code

Public Sub New()

    InitializeComponent()

    Dim dttemp As DataTable = New DataTable
    With dttemp.Columns
        .Add("ID")
        .Add("일자")
        .Add("동")
        .Add("호")
    End With

    dttemp.Rows.Add(1, "2020-04-13", "2101", "101")
    dttemp.Rows.Add(2, "2020-05-20", "2101", "1301")
    dttemp.Rows.Add(3, "2020-04-13", "2101", "1302")
    dttemp.Rows.Add(4, "2020-05-22", "2101", "2002")
    dttemp.Rows.Add(5, "2020-12-11", "2101", "201")
    dttemp.Rows.Add(6, "2020-12-11", "2101", "801")
    dttemp.Rows.Add(7, "2020-12-11", "2101", "801")

    DataGridView1.DataSource = dttemp

End Sub

 

 

Sort 정렬

C# Code

private void Sort_test()
{
    DataTable dt = GetTable(); 
    DataTable dt2 = dt.Clone();
    dt2.Columns["동"].DataType = Type.GetType("System.Int32");
    dt2.Columns["호"].DataType = Type.GetType("System.Int32");

    foreach (DataRow dr in dt.Rows)
    {
        dt2.ImportRow(dr);
    }
    dt2.AcceptChanges();
    DataView dv = dt2.DefaultView;
    dv.Sort = "동 ASC, 호 ASC";
}

 

 

VB.NET Code

Private Sub Sort_test()

    ' DataGridView에 DataSource를 DataTable로 
    Dim dt As DataTable = TryCast(DataGridView1.DataSource, DataTable)

    ' dt를 복제하여 dt2를 새로 만든다. (Clone을 하면 RowValue들은 복제되지 않고 껍데기만 복사 됨)
    Dim dt2 As DataTable = dt.Clone

    ' 기존 동, 호 컬럼을 Integer 형으로 변경 한다. 
    ' * 기존 컬럼이 String형식이어 원하는 방식으로 정렬이 되지 않아 변경
    dt2.Columns("동").DataType = Type.GetType("System.Int32")
    dt2.Columns("호").DataType = Type.GetType("System.Int32")

    ' dt를 반복하여 dt의 row를 dt2에 채운다.
    For Each dr As DataRow In dt.Rows
        dt2.ImportRow(dr)
    Next

    ' datatable update
    dt2.AcceptChanges()

    ' 정렬 한다.
    Dim dv As DataView = dt2.DefaultView
    dv.Sort = "[동] asc, [호] asc"

    ' datagridview.datasource에 반영한다.
    DataGridView1.DataSource = dv.ToTable


End Sub



728x90
반응형