按日期降序排序

时间:2013-07-29 03:42:26

标签: c# sql winforms

我想在Gridview中以降序显示日期作为默认值。

DataTable dt = new DataTable();
SqlDataAdapter adp = 
   new SqlDataAdapter("SELECT Customer.CustomerID, Customer.lastname, Customer.firstname, 
                              Ticket.Date, Ticket.Store, Ticket.Amount, Ticket.NoStub " +
                      "FROM Customer INNER JOIN Ticket ON Customer.CustomerID = Ticket.CustomerID 
                       WHERE Customer.CustomerID like " + txtCustomerID.Text, cn);
adp.Fill(dt);
gvHistory.DataSource = dt;

4 个答案:

答案 0 :(得分:2)

只需添加:

 order by Ticket.Date desc

到sql语句的末尾,如下所示:

DataTable dt = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter("SELECT Customer.CustomerID,             Customer.lastname, Customer.firstname, Ticket.Date, Ticket.Store, Ticket.Amount, Ticket.NoStub " +
                                                "FROM Customer INNER JOIN Ticket ON Customer.CustomerID = Ticket.CustomerID WHERE Customer.CustomerID like " + txtCustomerID.Text + " order by Ticket.Date desc", cn);
        adp.Fill(dt);
        gvHistory.DataSource = dt;

答案 1 :(得分:1)

正如@Adels的回答,你可以通过改变你的sql语句来订购,如果你想通过代码来做。尝试DataGridView.Sort方法,如下所示

gvHistory.Sort(gvHistory.Columns["ColumnName"], ListSortDirection.Descending);

答案 2 :(得分:1)

  1. 我建议在数据网格上使用Sort函数,正如Damith推荐的那样
  2. 不要直接将用户参数放入SQL语句。您必须使用WHERE Customer.CustomerID like @customerId,然后使用name = @customerId and value = txtCustomerID.Text向命令添加参数。这1)防止用户输入破坏数据库,2)防止膨胀SQL计划缓存。

答案 3 :(得分:0)

System.Data.DataTable dt = new System.Data.DataTable();
System.Data.SqlClient.SqlDataAdapter adp = new System.Data.SqlClient.SqlDataAdapter(
                      "SELECT Customer.CustomerID,
                              Customer.lastname, 
                              Customer.firstname, 
                              Ticket.Date, 
                              Ticket.Store, 
                              Ticket.Amount,
                              Ticket.NoStub " +
                      "FROM Customer INNER JOIN Ticket ON 
                              Customer.CustomerID = Ticket.CustomerID WHERE         
                              Customer.CustomerID like " + txtCustomerID.Text + " 
                              order by Ticket.Date desc", cn);
adp.Fill(dt);
gvHistory.DataSource = dt;