why i cant bind gridview directly from ListItemCollection Object? - sharepoint

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();

Related

SharePoint - programmatically add list items can't set ID

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();
}

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();

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();
}

Sharepoint Custom List with TimeStamp Field

I'm making a custom SharePoint List. I need a TimeStamp Field, but the only available type, by default, is DateTime.
Any help?
I think you would need to create a custom field type so that you can control the display of a DateTime type and validation etc - see this blog post for more info
I had the same problem in Sharepoint 2010 and solved it. Posting in case someone else finds this useful :)
To achieve this one must use the "Calculated" columntype.
From GUI:
Create new column
Pick type "Calculated".
Select "Created" column and add to formula.
Save.
From code:
As far as I can tell, there is two options to achieve this:
Access the "Created" and either set it's ShowInDisplayForm property to true or add the column to a view (for example the DefaultView).
Create a calculated column that points to the "Created" column, just as the GUI-example does. The trick is to set the "Formula" & the "OutputType" properties.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.RootWeb)
{
SPList list = web.Lists["test"];
string fieldName = list.Fields.Add("Timestamptest", SPFieldType.Calculated, false);
SPFieldCalculated field = list.Fields[fieldName] as SPFieldCalculated;
field.Formula = "=Created";
field.OutputType = SPFieldType.DateTime;
field.ShowInEditForm = false;
field.Update();
list.Update();
SPView defaultView = list.DefaultView;
defaultView.ViewFields.Add(field);
defaultView.Update();
}
}
});

Resources