Friday 13 April 2007

Add a new look-up type list item to your list programmatically

It's easy to add a new item into your list by simply assigning string values to your list which is , actually just a string. But if you want to add a listitem which actually is a reference or look-up to another list data in your sharepoint site? if you pass it in with a string, you will see error message like this. :

Invalid data has been used to update the list item. The field you are trying to update may be read only.


in your debugging message either in your event viewer or your IDE. It's as you expected , the value you inserted needs to be casted into correct type. So for example, your field is a look-up field referencing people and group list data in your site. You should use SPUser to cast the type, I use the current user for demo purpose.


SPSite mySite = new SPSite("http://yoursite");

//get your top-level site collection
//or fill in the param if you want to specify sub-site
SPWeb web = mySite.OpenWeb();
SPList targetList = web.Lists["Target List"];

//initiate new list item as usual
SPListItem newItem = targetList.Add();

//create a SPUser for current login
SPUser approver = web.Users["User_Name"];
newItem["Approver"] = approver;




this way you will be safe from casting errors.

No comments: