SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In one of my webparts, I have a ListViewByQuery displaying some elements (or all) of a specified list. The SPQuery is built dynamically depending on the search fields.

Here is how I build the SPQuery :

var list = SPContext.Current.Web.Lists["gpProjects"];
SPQuery query = new SPQuery(list.DefaultView);

query.ViewFields = "<FieldRef Name=\"Title\" /><FieldRef Name=\"departments\" />";
query.Query = "<OrderBy><FieldRef Name='Title' Ascending='true' /></OrderBy>";

listView.List = list;
listView.Query = query;

It works well, but now I need to use this query to get the items from the SPList:

var elements = list.GetItems(listView.Query).GetDataTable();

But it doesn't work. I got the following error : "Cannot complete this action. Please try again. "

Very helpful.

This doesn't only arises when there are no conditions on the query.

Does someone have an idea on how to make that working ?

I read somewhere that I have to impersonate myself in the webpart, but it didn't worked.

share|improve this question
up vote 2 down vote accepted

Why do you create SPQuery based on view? You're defining explicitely the fields to return and the query. So can you use parameterless SPQuery constructor? Maybe there's some conflicts betweeb view settings and your new query conditions.

share|improve this answer
Oh my god, I'm feeling so stupid... I just had to get the query string and put it in a new SPQuery and it worked well. Thanks a lot. – Baptiste Wicht Feb 11 '12 at 14:29

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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