简体   繁体   English

网格视图过滤数据

[英]grid view filtered data

I am interested in getting all the data a user sees in a grid view, after he applies some filters. 我对获取用户在应用某些过滤器后在网格视图中看到的所有数据感兴趣。 For example, the original grid's datasource contains 10 records, but the user apply a filter after which only 5 are still being displayed, I want to take those 5 and put them in a list. 例如,原始网格的数据源包含10条记录,但是用户应用了一个过滤器,之后仍仅显示5条记录,我想将这5条记录放在列表中。 How can this be accomplished? 如何做到这一点?

Assuming your grid is bound a some collection, then on postback, you can grab the datasource of the gridview, apply your filters, and save it to a new collection. 假设网格绑定了一个集合,然后回发,则可以获取gridview的数据源,应用过滤器,然后将其保存到新集合中。

Something like: 就像是:

var datasource = yourGridView.DataSource as List<someType>;
var filteredResults = datasource.Where( ... ); // apply your filters inside the Where

Obviously, replace the example variable names / types with what you're using in your code. 显然,将示例变量名称/类型替换为您在代码中使用的名称/类型。

Heres a nice little example of a kind of built in way to filter grid views: 这里是一个很好的小例子,展示了一种用于过滤网格视图的内置方式:

protected void btnSearch(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("MyConn");
    SqlCommand cmd = new SqlCommand();
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();

    cmd.Connection = con;
    cmd.CommandText = "SELECT * FROM CustomerTable WHERE NumberOfCustomer = @NumberOfCustomer";
    cmd.Parameters.AddWithValue("NumberOfCustomer", TextBox1.Text);

    try
    {
        con.Open();
        sda.Fill(dt);
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
    finally
    {
        con.Close();
    }

    GridView1.DataSource = dt;
    GridView1.DataBind();
}

And then to bind the datasource to a list: 然后将数据源绑定到列表:

protected void bindToList(object sender, EventArgs e)
{
    var datasource = GridView1.DataSource as List<Customers>;

    if ( !IsPostBack )
    {
        DropDownList ddl = new DropDownList();
        ddl.DataTextField = "Name";
        ddl.DataValueField = "Id";
        ddl.DataSource = datasource;
        ddl.DataBind();

        ddl.SelectedValue = list.Find( o => o.Selected == true ).Id.ToString();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM