在DataGrid中创建排序列

/// <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("没有任何设备");
   }
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值