您好我正在使用gridview查看数据库中的数据。现在我需要对它进行排序我的代码是下面的。
protected void Page_Load(object sender, EventArgs e)
{
GetDataTable();
}
public void GetDataTable()
{
string CS = ConfigurationManager.ConnectionStrings["FacebookConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "select Distinct F_Name AS [First Name], S_Name AS [Sur Name], E_Mail AS [Email], Day+'-'+Month+'-'+Year AS [Birthday], Gender AS [Gender] from Users ";
cmd.CommandType = CommandType.Text;
if (con.State == ConnectionState.Closed)
con.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable("Users");
dt.Load(dr);
grdUser.DataSource = dt;
grdUser.DataBind();
cmd.Dispose();
con.Close();
}
}
}
protected void grdUser_Sorting(object sender, GridViewSortEventArgs e)
{
}
protected void grdUser_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdUser.PageIndex = e.NewPageIndex;
GetDataTable();
}
和aspx代码如下:
<div class="container" style="padding-right: 15px; padding-left: 15px; margin-top:auto">
<asp:GridView ID="grdUser" runat="server" CssClass="table table-responsive table-condensed table-striped table-hover" OnPageIndexChanging="grdUser_PageIndexChanging" OnSorting="grdUser_Sorting" PageSize="3" AllowPaging="True" AllowSorting="True"
ForeColor="Black">
<PagerSettings FirstPageText="First" LastPageText="Last" Mode="NumericFirstLast" PageButtonCount="4" />
</asp:GridView>
</div>
我是编程的新手,我已经尝试了很多方法,但我没有得到任何结果请帮助
答案 0 :(得分:0)
使用此查询
cmd.Connection = con;
cmd.CommandText = "select Distinct F_Name AS [First Name], S_Name AS [Sur Name], E_Mail AS [Email], Day+'-'+Month+'-'+Year AS [Birthday], Gender AS [Gender] from Users order by F_Name ";
cmd.CommandType = CommandType.Text;
答案 1 :(得分:0)
在SQL查询中使用ORDER BY Clause。默认情况下,排序顺序为升序。如果您需要按降序排序,请使用ORDER BY F_Name DESC
SELECT DISTINCT F_Name AS [First Name]
,S_Name AS [Sur Name]
,E_Mail AS [Email]
,Day + '-' + Month + '-' + Year AS [Birthday]
,Gender AS [Gender]
FROM Users
ORDER BY F_Name