Thursday, November 22, 2007

SPQuery inside a foreach bucle

Today I have found a strange behavior of the SPQuery class. My code has the following structure:


SPList list = web.Lists["MyList"];
SPQuery query = new SPQuery();
foreach (DataRow row in table.Rows)
{
query.Query = "<Where>Some CAML Query with a row dependant condition</Where>";
SPListItemCollection items = list.GetItems(query);

}

After the first iteration, the SPListItemCollection items always contains the same items, although the Query property of the query has been changed in the bucle. To resolve it I have putted the initialization of the SPQuery inside the bucle:


SPList list = web.Lists["MyList"];
foreach (DataRow row in table.Rows)
{
SPQuery query = new SPQuery();
query.Query = "<Where>Some CAML Query with a row dependant condition</Where>";
SPListItemCollection items = list.GetItems(query);

}

And now all works normally.

3 comments:

Arsalan said...

Thanks a lot! That was so much helpful. I spent more than 4 hours trying to resolve this but couldn't find where i was wrong ... now it works perfectly OK.

Regards,
Your friend from Pakistan

Ani said...

Hello

I am new to code. In document library I am uploading variosu infopatah forms. This forms fields are populating well in document library. It has field called 'mystatus'. Here I want to send a mail to a group/user where if any list item having 'mystatus' field is empty or null. This I want to implement on daily basis, it is like schedule workflow.

Any idea on this.

Please help me, I am stuck here. I am not comfortable with VS 2005.

Anu

Àlex said...

Ani,
The best solution is to implement a custom timer job definition. Andrew Connell wrote an excellent article about this process: http://msdn.microsoft.com/en-us/library/cc406686.aspx.

 
Online Visitors