sorting filtered data in asp.net listview

Posted by user791345 on Stack Overflow See other posts from Stack Overflow or by user791345
Published on 2012-03-19T18:00:45Z Indexed on 2012/03/19 18:04 UTC
Read the original article Hit count: 317

Filed under:

I've created a listview that's filled up with a list of guitars from the database on page load like so:

protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["GuitarsLTDBConnectionString"].ToString());
        SqlCommand cmd = new SqlCommand("SELECT * FROM Guitars", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText, con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        lvGuitars.DataSource = dt;
        lvGuitars.DataBind();
    }

The following code filters that list of guitars by a certain Make when the user checks the checkbox corresponding to that make

protected void chkOrgs_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataTable dt = (DataTable)lvGuitars.DataSource;
        DataView dv = new DataView(dt);
        if (chkOrgs.SelectedValue == "Gibson")
        {
            dv.RowFilter = "Make = 'Gibson' OR Make='Fender'";
        }
        lvGuitars.DataSource = dv.ToTable();
        lvGuitars.DataBind();
    }

Now, what I want to do is be able to sort the latest data that is present within the listview. Meaning, if sort is clicked before filtering, the it should sort all data. If sort is clicked after filtering, it should sort the filtered data. I'm using the following code, which is triggered upon a LinkButton click

protected void lnkSortResults_Click(object sender, EventArgs e)
    {
        DataTable dt = (DataTable)lvGuitars.DataSource;
        DataView dv = new DataView(dt);
        dv.Sort = "Make ASC";
        lvGuitars.DataSource = dv.ToTable();
        lvGuitars.DataBind();
    }

The problem is that all the data that the listview was loaded with before any filtering is sorted, and not the latest filtered data. How can I change this code so that the latest data available in the listview is the one that's sorted?

Thanks

© Stack Overflow or respective owner

Related posts about sorting