SharePoint - programmatically add list items can't set ID - sharepoint

I need to create new list item in sharepoint 2016 but while creating, on ID field, i'm getting this error: "This field cannot be updated". I'm not updating anything and i checked the list and it was empty too.
I left this field empty and it has 0 value by defualt like when i'm inserting new row in sql tables.

The ID field is a system field which will increase automatically when new item created, so no need to set ID field value, here is a code snippet which add new item with default Title field and ID field will be automatically generated with 1 as it is a empty list previously:
SPSite site = new SPSite("http://demoaam.contoso2016.com/sites/dev");
using (SPWeb web=site.OpenWeb() )
{
SPList list = web.Lists["TestList"];
SPListItem newitem = list.AddItem();
newitem["Title"] = "NewItemTitle";
newitem.Update();
}

Related

How to retrieve publishing rollup image path in sharepoint object model

While using the traditional code to retrieve list items in SharePoint, Everytime I get an error whenever I try to read the value of publishing rollup image. My Code is as below:
SPWeb mySite = SPContext.Current.Web;
SPList myList = mySite.Lists["Quick Links"];
SPListItemCollection myItems = myList.Items;
for (int i = 0; i < myItems.Count; i++)
{
SPListItem item = myItems[i];
pageHTML += item["PublishingRollupImage"].ToString(); //error
}
use this method
item.GetFormattedValue("Rollup Image");
The array access (bracket) notation to access a field value accepts one of three values between the brackets:
The field's GUID (as a System.Guid)
The field's display name (as a string)
The field's index in the item's fields collection (as an integer)
When accessing a field by its internal name instead of by its display name, you should use the dedicated GetFieldByInternalName method to retrieve the field from the fields collection, then use the retrieved field's Id property to get the field's GUID and use that in the brackets.
item[item.Fields.GetFieldByInternalName("PublishingRollupImage").Id].ToString();

why i cant bind gridview directly from ListItemCollection Object?

I'm new to SharePoint List and i need to bind gridview using list item collection object like below
SPList splEmployees = SPContext.Current.Web.Lists["Employees"];
spgvEmployees.DataSource = splEmployees.Items;//or splEmployees.GetItems();
spgvEmployees.DataBind();
this is not success when i bind it to gridview contains Title and EmployeeID columns but it success when i remove EmployeeID column.
Try to use a SPDataSource instead.
SPDataSource myDatas = new SPDataSource();
myDatas.List = splEmployees;
spgvEmployees.DataSource=myDatas;
spgvEmployees.DataBind();

Save lookup value to SharePoint 2010

I've figured out how to add a record into a library. The only thing I am trying to figure out is how (or maybe where) do I save a user's selection from a lookup list?
In the below code snippet, I am saving a new list item. It saves without error, but the fields "AwardType" and "AwardReason" are lookup fields and, although I do not get an error, nothing gets saved to them. How do I save to a lookup field selection from a user?
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{
using (FileStream fs = (new FileInfo(fileUpload.PostedFile.FileName)).OpenRead())
{
SPList list = web.Lists["Awards"];
Hashtable ht = new Hashtable();
ht.Add("wfRecipientName", txtRecipientName.Text);
ht.Add("Office", txtOrganization.Value);
ht.Add("AwardType", ddAwardTypes.SelectedValue);
ht.Add("AwardReason", ddAwardReasons.SelectedValue);
SPFile destfile = list.RootFolder.Files.Add(fileUpload.FileName, fs, ht, false);
}
}
}
Storing a lookup's value is done with SPFieldLookupValue(ID, Value).
You need to store the object returned by this method in a list item field, not a property via a hash table. In my example below, Awards list is document library and AwardType is a field of type lookup.
SPList list = web.Lists["Awards"];
Hashtable ht = new Hashtable();
ht.Add("Office", "Chicago"); // standard property
SPFile file = list.RootFolder.Files.Add(System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName), fs, ht, true);
SPListItem item = file.Item; // get the item for the just-added file.
// assign the lookup column using SPFieldLookupValue
item["AwardType"] = new SPFieldLookupValue(
Int32.Parse(DropDownList1.SelectedValue),
DropDownList1.Text);
item.Update(); // to save the lookup column.
Interestingly, the line
SPListItem item = file.Item; // get the item for the just-added file.
is key.
I had trouble when I used the code below - the lookup did not update consistently!?
file.Item["AwardType"] = new SPFieldLookupValue(
Int32.Parse(DropDownList1.SelectedValue),
DropDownList1.Text);
You must add the SPFieldLookUpValue as string to the HashTable, not the value of the Lookup.
Properties stored on HashTable other than int, string, date will not be parsed on Document creation.
SPFieldLookupValue v = new SPFieldLookupValue(item["lookUpField"].ToString());
Hashtable documentProperties = new Hashtable();
documentProperties.Add("key", v.ToString());
SPFile file = docLib.RootFolder.Files.Add("fileName", memoryStream, documentProperties, true);
The same can be done with complex objects as SPUser.
SPFieldUserValue userValue = new SPFieldUserValue(web, web.CurrentUser.ID, web.CurrentUser.LoginName);
documentProperties.Add("SPuSER", userValue.ToString());

Sharepoint webpart combobox of lists

I have a webpart that works off of a list but what I'm trying to do create a dropdown that contains a list of sharepoint lists so that when the user edits the page and selects 'modify shared webpart' they are able to choose a list item and that gets parsed back to the webpart.
Any examples or links to examples appreciated!
Thanks
Dan
What you are looking for is called a Toolpart. Take a look at this example for a tutorial on how to create one.
Overall, your general steps will be:
Create your custom Toolpart class inheriting from Microsoft.SharePoint.WebPartPages.ToolPart
In your custom Toolpart, override CreateChildControls, write the code to iterate over the lists in your SPWeb, and add those to a DropDownList
In your webpart, override GetToolParts and add your custom ToolPart so that it shows up in the right hand side
It sounds like you want to create a custom editor part. In the part you would have one dropdown that shows the names of the lists (you probably want to filter hidden and empty lists) and, when an item is selected from the list, a second dropdown shows the Title column of the items from the selected list.
Here's some code (edited here, so it will need to be cleaned up) to help you get started:
protected Page_Load(...)
{
if (IsPostBack) return;
var web = SPContext.Current.Web;
var query = from list in web.Lists
where list.Hidden == false && list.ItemCount == 0
select list;
DropDownList1.DataSource = query;
DropDownList1.DataTextField = "Title";
DropDownList1.DataBind();
}
protected DropDownList1_SelectedIndexChanged(...)
{
var web = SPContext.Current.Web;
var listName = DropDownList1.Text;
var list = web.Lists[listName];
var table = list.Items.GetDataTable();
DropDownList2.DataSource = table;
DropDownList2.DataTextField = "Title";
DropDownList2.DataValueField = "ID";
DropDownList2.DataBind();
}

Read/write Person metadata from a Word doc stored in SharePoint using VBA or VSTO?

Scenario: Document library in SharePoint with column x of "Person or Group" type. From within a VBA macro (or VSTO add-in) we're trying to access the MetaProperty on the document to set/get the user name. Any attempt to access the value via the ContentTypeProperties collection throws a
Type MisMatch error (13).
The Type property of the MetaProperty object says it's msoMetaPropertyTypeUser. I cannot find any examples of how to work with MetaProperties of this type. Anyone have any experience with this?
Thanks!
You should be able to just do something like this:
using (SPSite site = new SPSite("http://yoursite/subsite"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["DocLibraryName"];
SPListItemCollection items = list.GetItems(list.Views["All Documents"]);
foreach (SPListItem item in items)
{
item["Modified By"] = "Updated Value";
}
}
}
Any metadata for a document should be available by indexing the column name of the SPListItem.
I did it.
The trick here is actually to know that if you put a string corresponding to the user index in MOSS users in the custom property of the Word document, MOSS will recognize it and find the corresponding user to map the field.
so you just need to call http:///_vti_bin/usergroup.asmx
use the function GetUserInfo and retrieve the user index (ID) from it.
MOSSusergroup.UserGroup userGroupService = new MOSSusergroup.UserGroup();
userGroupService.Credentials = System.Net.CredentialCache.DefaultCredentials;
System.Xml.XmlNode node = userGroupService.GetUserInfo(userLogin);
string index = node.FirstChild.Attributes["ID"].Value;

Resources