I would like to know how can I filter information in SharePoint list (Library of documents) programmatically. I have tried 2 ways but they don't solve my problem:

  • Using the string lsWebPart.FilterString. It creates a filter, but then the user is able to remove that filter in the interface, so it's not a good solution.

  • Using SPView.Query. It modifies the view but I don't need to modify it, just to show different filters based on some user parameters.

In my site I would like to filter the same library of document by a column called 'Nationality'. So depending on the nationality of the user connected (I retrieve that from Active Directory) I would show different data. If I can' make that via code, I would need to create a view for each country (but that is not efficient and will need constant updates for new countries).

Are there other possible ways to filter the information of a list in my code?


Do you mean something like that 'Aviw'?

  SPListView docview = list.Views["MyView"];       
  var docquery = new XElement("Where",
           new XElement("Eq",
           new XElement("FieldRef", new XAttribute("Name", "Nationality")),
           new XElement("Value", new XAttribute("Type", "String"), "xxxx")

           docview.Query = docquery;
           lsWebPart.ViewGuid = docview.ID.ToString("B").ToUpper();


SPList list = web.Lists["mylist"];//Evalee Docs
ListViewByQuery listviewByQuery = new ListViewByQuery();
listviewByQuery.List = list;
SPQuery query = new SPQuery(listviewByQuery.List.DefaultView);
query.Query = "Here your CAML expression";
listviewByQuery.Query = query;
  • 1
    How does this work? Do I have to create webpart with a document library in it and apply this code??
    – Perplexed
    Apr 30, 2012 at 15:53

1 Answer 1


Use SPGridView or SPListViewByQuery instead of SPView. http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webcontrols.listviewbyquery.aspx.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.