/// <summary>
/// 排序,首先设置BoundColumn中的SortExpression
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
private void DataGrid1_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
Session.Add("sorting",e.SortExpression);
if(Session["sortDirection"] == null)
{
Session.Add("sortDirection","ASC");
}
else
{
if(Session["sortDirection"].ToString() == "ASC")
{
Session["sortDirection"] = "DESC";
}
else
{
Session["sortDirection"] = "ASC";
}
}
}
<asp:BoundColumn DataField="DeviceID" SortExpression="DeviceID" HeaderText="设备编号"></asp:BoundColumn>
然后编写一个加载数据的函数:
/// <summary>
/// 加载数据,绑定到DataGrid
/// </summary>
private void LoadData()
{
string strCmd = "";
if(Session["sorting"] == null)
{
strCmd = "SELECT * FROM Jxt_DeviceManage_DeviceBasicData";
}
else
{
strCmd = "SELECT * FROM Jxt_DeviceManage_DeviceBasicData ORDER BY "+Session["sorting"].ToString()+" "+Session["sortDirection"].ToString();
}
conn = new SqlConnection(strConn);
adapter = new SqlDataAdapter(strCmd,conn);
ds = new DataSet();
adapter.Fill(ds);
DataTable dt = ds.Tables[0];
DataColumn dataCol = new DataColumn("RowNumber",Type.GetType("System.Int16"));
dt.Columns.Add(dataCol);
for(int i=0;i<dt.Rows.Count;i++)
{
if(0 == i)
{
dt.Rows[i][dataCol] = 1;
}
else
{
dt.Rows[i][dataCol] = Convert.ToInt16(dt.Rows[i-1][dataCol])+1;
}
}
DataView dv = new DataView(dt);
DataGrid1.DataSource = dv;
DataGrid1.DataKeyField = "DBID";
this.DataGrid1.DataBind();
if(this.DataGrid1.Items.Count < 1)
{
this.DataGrid1.Visible = false;
Response.Write("没有任何设备");
}
}