C# sort data by DataTable.Select()
Posted: 22/02/2011 3:17 pm
เพื่อนๆเคย sort dataTable ด้วย .DataView() เเต่ไม่ได้ผลบ้างรึเปล่าครับ
ผมเเนะนำให้เปลี่ยนมาใช้ DataTable.Select() แทนครับ รับรองผล 100 %
ในตัวอย่างนี้คือจะ sort ข้อมูลด้วยคอลัมน์ vote โดยเรียงจากจำนวน vote มากสุดอยู่เเถวเเรก
ผมเเนะนำให้เปลี่ยนมาใช้ DataTable.Select() แทนครับ รับรองผล 100 %
ในตัวอย่างนี้คือจะ sort ข้อมูลด้วยคอลัมน์ vote โดยเรียงจากจำนวน vote มากสุดอยู่เเถวเเรก
Code: Select all
private void BlahBlah()
{
if (dtlocal.Rows.Count > 0)
{
dtlocal = ManualSortDataTable(dtlocal, "Vote", "DESC");
GridView1.DataSource = dtlocal;
GridView1.DataBind();
}
}
private DataTable ManualSortDataTable(DataTable table, string colName, string direction)
{
DataTable dt = table.Clone();
dt = table.Copy();
dt.Rows.Clear();
DataRow[] rows = table.Select("", string.Format("{0} {1}", colName, direction));
foreach (DataRow r in rows)
{
dt.ImportRow(r);
}
return dt;
}