如何在 asp.net 中对网格视图进行排序
本文关键字:视图 网格 排序 asp net | 更新日期: 2023-09-27 17:57:00
嗨,我正在使用网格视图查看数据库中的数据。 现在我需要对其进行排序,我的代码是波纹管。
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>
我是编程新手,我已经尝试了很多方法,但我没有得到任何结果,请帮助
使用此查询
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;
在 SQL 查询中使用 ORDER BY 子句。默认情况下,排序顺序是升序。如果需要按降序排序,请使用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