Custom Filter Web Part to filter/update ListView Web Part

1.4k views Asked by At

Scenario : I need Refresh/Filter the Items/records displayed in List View Web Part on the same page based on selected filters. So I created Visual Web Part and tried to modify the View of List View Web Part Programmatically. So far i have reached till here :

string spListName = "Job";

protected void BtnSearchClick(object sender, EventArgs e)
{
    try
    {
    SPWeb oWebsite = SPContext.Current.Web;
    SPList oList = oWebsite.Lists[spListName];
    XsltListViewWebPart xsltWP = null;

    SPWebPartManager wpManager = WebPartManager.GetCurrentWebPartManager(Page) as SPWebPartManager;

    //Code to Find List View Web Part on Page
    foreach (System.Web.UI.WebControls.WebParts.WebPart wp in wpManager.WebParts)
    {
        if (wp.GetType().Name == "XsltListViewWebPart")
            xsltWP = wp as XsltListViewWebPart;
    }

    oWebsite.AllowUnsafeUpdates = true;

    StringBuilder strbPreQuery = new StringBuilder("<Where><Eq>");

    StringBuilder strbPostQuery = new StringBuilder("</Value></Eq></Where>");

    string strQueryKeyword = "<FieldRef Name='Customer' /><Value Type='Lookup'>";

    SPQuery oQuery = new SPQuery();
    oQuery.Query = strbPreQuery.ToString() + strQueryKeyword + txtCustomer.Text + strbPostQuery.ToString();
    SPListItemCollection itemCol = oWebsite.Lists[spListName].GetItems(oQuery);

    PropertyInfo pi = xsltWP.GetType().GetProperty("ContextView", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
    SPView view = (SPView)(pi.GetValue(xsltWP, null));

    view.Query = oQuery.Query;
    view.Update();

    wpManager.SaveChanges(xsltWP);
    xsltWP.DataBind();

    oWebsite.AllowUnsafeUpdates = false;

}

catch (Exception ex)
{
    Response.Write(ex);
}
}

The Above code works but now I am facing following problems :

  1. The results updation requires page refresh so If I add following code, results are updated but filter values in visual web part is lost.

    this.Context.Response.Redirect(this.Context.Request.Url.ToString());
    
  2. Filtered applied by one user is also reflected to another user.

Can some please help in to address these two problems I have ? that is I want

  1. To preserve the filter values and results to be modified at the same time
  2. The filtering should be only for one user and not for all.

Any help in this regards will be appreciated.

1

There are 1 answers

3
Aki Telesforo On

Create a SPQuery that will hold the default value of the view. then after passing the value, Use this to revert back the default query of the view.

SPView _view;

protected void Page_Unload(object sender, EventArgs e)
{
    //your code
    SPView view = (SPView)(pi.GetValue(xsltWP, null));
    view.Query = _view.Query;
    view.Update();
}