我想在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;
答案 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)
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;