這次的主題是排序,排序的元件是DataView。一般而言,用SQL本身的語法就可以排序,但有時仍會遇到資料表合併要排序的場合,這時SQL的效率就會比較差,這時候用元件排序會比較有效率,這是本篇文章要探討的主題。這個題目其實別的部落格也有提到,這裡只是修改範例寫在這邊。
程式一開始是執行private void process_select_ori(),例如上圖的結果,它是照id排序,按下Button後執行private void process_select(),結果如下圖:
可以看到,SortTables(ref ds, "postTime DESC");這行的作用,簡單地說就是按照欄位下語法排序,這裡是用時間後者為最上面的排序方式,以上結果就當參考。
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["peomConnectionTest1"].ConnectionString);
//
protected void Page_Load(object sender, EventArgs e)
{
process_select_ori();
}
protected void Button1_Click(object sender, EventArgs e)
{
process_select();
}
//排序副程式
private void SortTables(ref DataSet ds, string sort)
{
foreach (DataTable dt in ds.Tables)
{
DataView dv = new DataView(dt);
dv.Sort = sort;
DataTable dtSorted = dv.ToTable();
ds.Tables[dt.TableName].Clear();
ds.Tables[dt.TableName].Merge(dtSorted);
}
}
private void process_select()
{
string strSQL = " ";
strSQL += " SELECT [id],[title],[context],[postTime] ";
strSQL += " FROM [peom].[dbo].[DiscussionBoard] ";
strSQL += " order by id desc ";
conn.Open();
System.Data.DataSet ds = new System.Data.DataSet();
SqlCommand com = new SqlCommand(strSQL, conn);
SqlDataAdapter oleDbAdapter = new SqlDataAdapter(com);
oleDbAdapter.SelectCommand.CommandTimeout = 1000;
oleDbAdapter.Fill(ds);
SortTables(ref ds, "postTime DESC");//排序副程式
conn.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
}
private void process_select_ori()
{
string strSQL = " ";
strSQL += " SELECT [id],[title],[context],[postTime] ";
strSQL += " FROM [peom].[dbo].[DiscussionBoard] ";
strSQL += " order by id asc ";
conn.Open();
System.Data.DataSet ds = new System.Data.DataSet();
SqlCommand com = new SqlCommand(strSQL, conn);
SqlDataAdapter oleDbAdapter = new SqlDataAdapter(com);
oleDbAdapter.SelectCommand.CommandTimeout = 1000;
oleDbAdapter.Fill(ds);
conn.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
}
留言列表