DataView过滤数据行 排序

 

DataView过滤数据行

private void filterButton_Click(object sender, System.EventArgs e)
  {//过滤
   SqlConnection conn=new SqlConnection();
   conn.ConnectionString=ConfigurationSettings.AppSettings["ConnectionString"].ToString();
   conn.Open();
   string sql="select * from Products";
   SqlDataAdapter cmd=new SqlDataAdapter(sql,conn);
   ds=new DataSet();
   cmd.Fill(ds,"showTable");
   DataView dv=ds.Tables["showTable"].DefaultView;
   dv.RowFilter="ProductName like /'%"+name.Text+"%/'";   
   DataGrid1.DataSource=dv; 
   DataBind();
   cmd.Dispose();
   conn.Close();
   conn.Dispose();
  }

DataView多条件过滤

DataView dv=ds.Tables["showTable"].DefaultView;
   dv.RowFilter="ProductName like /'%"+name.Text+"%/' and ProductID="+name2.Text+"";   
   DataGrid1.DataSource=dv; 
   DataGrid1.DataBind();

DataView过滤状态行

DataView dv2=ds.Tables["showTable"].DefaultView;
   dv2.RowStateFilter=DataViewRowState.Deleted;//删除行
   DataGrid2.DataSource=dv2;
   DataGrid2.DataBind();

DataView dv2=ds.Tables["showTable"].DefaultView;
   dv2.RowStateFilter=DataViewRowState.CurrentRows;//目前行
   DataGrid2.DataSource=dv2;
   DataGrid2.DataBind();

通过状态行可以显示用户所做过的操作,从而决定是否更新数据库数据

DataView排序

SqlConnection conn=new SqlConnection();
   conn.ConnectionString=ConfigurationSettings.AppSettings["ConnectionString"].ToString();
   conn.Open();
   string sql="select * from Products";
   SqlDataAdapter cmd=new SqlDataAdapter(sql,conn);
   ds=new DataSet();
   cmd.Fill(ds,"showTable");
   DataView dv=ds.Tables["showTable"].DefaultView;
   dv.RowFilter="ProductName like /'%"+name.Text+"%/'";   
   dv.Sort="SupplierID DESC,ProductName DESC";
   DataGrid1.DataSource=dv; 
   DataGrid1.DataBind();
   cmd.Dispose();
   conn.Close();
   conn.Dispose();
DataGrid排序

private void DataGrid1_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
  {//排序
   SqlConnection conn=new SqlConnection();
   conn.ConnectionString=ConfigurationSettings.AppSettings["ConnectionString"].ToString();
   conn.Open();
   string sql="select * from Products";
   SqlDataAdapter cmd=new SqlDataAdapter(sql,conn);
   ds=new DataSet();
   cmd.Fill(ds,"showTable");
   dv2=ds.Tables["showTable"].DefaultView;
   dv2.Sort=e.SortExpression;
   DataGrid1.DataSource=dv2;
   DataGrid1.DataBind();
  }

DataGrid利用DataView过滤,排序(以下代码为网上收集)

DataSet ds = new DataSet();
SqlConnection conn =  new SqlConnection("server=localhost;uid=sa;pwd=sa;DataBase=pubs");
SqlDataAdapter ada = new SqlDataAdapter("select * from authors",conn);
conn.Open();
ada.Fill(ds,"a");
conn.Close();
DataView dv = new DataView();
dv.Table = ds.Tables[0];
dv.RowFilter = "au_fname like 'a%'";
dv.Sort = "au_id DESC";
tst.DataSource=dv;
tst.DataBind();

你可能感兴趣的:(.NET基础,datagrid,dataset,sql,string,object,cmd)