2010-10-25

ASP.NET GridView

做出可以指定欄位名稱欄位排序GridView:
//取得資料
private void loadData(string sortString){
DataTable dt = MyData.getAllDatas();
if (sortString != "")
        {
            dt.DefaultView.Sort = sortString;
        }
        GridView1.DataSource = dt;
        GridView1.DataBind();
}
//設定欄位名稱
private void generateTitle(DataTable dt){
string[] title = new string[] { "欄位A", "欄位B", "欄位C", "欄位D", "欄位E"};
        for (int i = 0; i < title.Length; i++)
        {
            dt.Columns[i].ColumnName = title[i];
        }
}
//GridView排序事件
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        string d = e.SortExpression;//需要排序的欄位名稱
        string sort = (string)ViewState[d];
        if (sort == null || sort == "" || sort == " ASC")
        {
            ViewState[d] = " DESC";//[排序方式]
        }
        else
        {
            ViewState[d] = " ASC";//[排序方式]
        }
        loadSyncMark(d + (string)ViewState[d]);//"[欄位名稱] [排序方式]"
    }
//網頁載入的用法
 protected void Page_Load(object sender, EventArgs e)
 {
   loadData("");
 }

沒有留言: