1

我想默认在 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

4 回答 4

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;
于 2013-07-29T03:44:55.840 回答
1
  1. 我建议按照 Damith 的建议在数据网格上使用排序功能
  2. 不要将用户参数直接放入 SQL 语句中。您必须使用WHERE Customer.CustomerID like @customerId,然后将参数添加到命令中,使用name = @customerId and value = txtCustomerID.Text. 这 1) 防止用户输入破坏数据库,2) 防止 SQL 计划缓存膨胀。
于 2013-07-29T04:16:48.043 回答
1

正如@Adels 回答的那样,如果您想通过代码进行操作,您可以通过更改您的 sql 语句来订购。试试DataGridView.Sort下面的方法

gvHistory.Sort(gvHistory.Columns["ColumnName"], ListSortDirection.Descending);
于 2013-07-29T03:55:55.757 回答
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;
于 2013-07-29T04:11:24.670 回答