Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I am getting an item by using GetItemById but I want to check before using it whether the item exists or not. I don't want to use a query as the main purpose of using GetItemById is performance.

itemid = Response.QueryString["loc"];
SPList mylist = myweb.GetList(SPUrlUtility.CombineUrl(myweb.ServerRelativeUrl, "/Lists/Location"));

If the item with the given itemid does not exist this throws an exception:

  SPListItem myitem = mylist.GetItemById(Convert.ToInt32(itemid));

Any ideas of how to achieve this?

share|improve this question
add comment

1 Answer 1

SPQuery by no way will make your code slow, infact every other SharePoint article on net advice you to use SPQuery to gain Performance. To make things still more interesting GetItemByID internally use SPQuery to fetch the Item back to you,following is part of code taken from the GetItemByID function

  SPQuery query = new SPQuery();
  query.Query = "<Where><Eq><FieldRef Name=\"ID\"></FieldRef><Value Type=\"Integer\">" + id.ToString(CultureInfo.InvariantCulture) + "</Value></Eq></Where>";

Important to note here is SPQuery has a Internal property called SingleItemId which takes Id of the Item Id you want to fetch, further tracing of how it being used cannot be found as the call finally lands up in COM Object.

Being said that you have two options Option 1:

Wrap your GetItemByID code inside the catch block and check for exception,if one occurs you can mark a flag to denote that Item Id is invalid and take action for it.

Option 2:Use SPQuery, you can test the time difference GetItemByID & using SPQuery, you will see that there is no and just a very very little time difference between two.

share|improve this answer
1  
Yeah great point. Often the internal API code can be very revealing. Thanfully we have .Net Reflector! –  Charles Lee Mar 14 '10 at 10:10
add comment

Your Answer

 
discard

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