[C#] Datatble排序 + DataView轉換為DataTable

  • 10794
  • 0

摘要:[C#] Datatble排序 + DataView轉換為DataTable

private void sort()
{
            DataTable dt = new DataTable();

            dt.Columns.Add("Column_1", typeof(string));

            dt.Columns.Add("Column_2", typeof(string));

            dt.Columns.Add("Column_3", typeof(string));

            dt.Columns.Add("Column_4", typeof(int));


            dt.Rows.Add("4", "四", "D", 4);

            dt.Rows.Add("1", "二", "C", 1);

            dt.Rows.Add("3", "一", "B", 3);

            dt.Rows.Add("2", "三", "A", 2);

            dt.Rows.Add("11", "一一", "ELEVEN", 11);

            dt.Rows.Add("0", "零", "O", 0);

            // 利用DataTable的DefaultView來做排序
            dt.DefaultView.Sort = "Column_4 ASC";


            // 但是此排序並非dt實際排序...須轉換
            DataTable tempDT = CreateTable(dt.DefaultView);

            GridView1.DataSource = tempDT;
            GridView1.DataBind();

}

 

// 把DataView轉換為DataTabl

public DataTable CreateTable(DataView obDataView)
{
            if (null == obDataView)
            {
                throw new ArgumentNullException
                ("DataView", "Invalid DataView object specified");
            }

            DataTable obNewDt = obDataView.Table.Clone();
            int idx = 0;
            string[] strColNames = new string[obNewDt.Columns.Count];

            foreach (DataColumn col in obNewDt.Columns)
            {
                strColNames[idx++] = col.ColumnName;
            }

            IEnumerator viewEnumerator = obDataView.GetEnumerator();
            while (viewEnumerator.MoveNext())
            {
                DataRowView drv = (DataRowView)viewEnumerator.Current;
                DataRow dr = obNewDt.NewRow();
                try
                {
                    foreach (string strName in strColNames)
                    {
                        dr[strName] = drv[strName];
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                obNewDt.Rows.Add(dr);
            }

            return obNewDt;

}

 






Y2J's Life:http://kimenyeh.blogspot.tw/