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.

1 Answer 1


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.

  • 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. Feb 11, 2012 at 14:29

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.