下面的代碼示例是排序GridView
形成與DataSet
。排序GridView形成與數據集
來源:http://www.highoncoding.com/Articles/176_Sorting_GridView_Manually_.aspx
但它不顯示任何輸出。 在sql連接中沒有問題。 我無法追查錯誤,請幫助我。 謝謝。
public partial class _Default : System.Web.UI.Page
{
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
private DataSet GetData()
{
SqlConnection cnn = new SqlConnection("Server=localhost;Database=Northwind;Trusted_Connection=True;");
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 5 firstname,lastname,hiredate FROM EMPLOYEES", cnn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression, string direction)
{
// You can cache the DataTable for improving performance
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
}
aspx頁面
asp:GridView ID="GridView1" runat="server" AllowSorting="True" OnSorting="GridView1_Sorting">
/asp:GridView>
在問題中的引用鏈接幫助我實現什麼我試圖用一個問題來做,GridView控件不返回任何行。解決方案是將「AutoGenerateColumns」屬性設置爲true。這適用於我的情況,因爲我不想隱藏任何列。 – Doreen 2017-01-18 22:28:57