Wednesday, 12 August 2015

Check if ListItem exist in SharePoint List by Id

We can get SPListItem by id directly using the method

list.GetItemById(id)

But if the item with given id does not exists then the above given method will throw an exception as it will not get the item of given id.

Hence, before getting the id we can check whether the ListItem of given id exists or not using LINQ query as given below

int count = (from SPListItem item in list.Items
                    where Convert.ToInt32(item["ID"]) == id
                     select item).Count();

The above code will return the count if the item with given id exists. If the item does not exist then it will return 0.

Based on the count you can proceed with further execution.

Wednesday, 5 August 2015

Add folder in SharePoint list programatically

Below is the code snippet to add folder in SharePoint list

SPList lst = web.GetList("ListRelativePath");
if (lst != null)
{
        SPContentType spContTyp =lst.ContentTypes["Folder Content Type Name"];

        SPListItem folderItem = lst.Items.Add(lst.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder);

        folderItem["Title"] = "foldername";
        folderItem.Update();

}

Read values from SharePoint people picker control in visual web part

Below is the code snippet to read values from SharePoint people picker control and update list item

 SPFieldUserValueCollection valueColl = new SPFieldUserValueCollection();

for (int i = 0; i < peoplePickerControlId.ResolvedEntities.Count; i++)
{
       PickerEntity peEntity = (PickerEntity)peoplePickerControlId.ResolvedEntities[i];
       SPUser user = SPContext.Current.Web.EnsureUser(peEntity.Key);
       SPFieldUserValue userVal = new SPFieldUserValue(web, user.ID, user.Name);
       valueColl.Add(userVal);
}

item["User"] = valueColl;

Assign values to people picker control in SharePoint visual webpart

Below is the code snippet to read users from User and group field and assigning the same to the people picker control in form


                SPFieldUserValueCollection trainerColl = new SPFieldUserValueCollection(web, Convert.ToString(ItemColl[0]["User"]));

                List<PickerEntity> trainersEntity = new List<PickerEntity>();

                foreach (SPFieldUserValue spuserval in trainerColl)
                {

                    SPUser userToassign = spuserval.User;

                    PickerEntity entity = new PickerEntity();

                    PeopleEditor pe = new PeopleEditor();

                    entity.EntityData["Account Name"] = spuserval.User.LoginName;
                    entity.EntityData["SPUserId"] = spuserval.User.ID;
                    entity.EntityDa"Email"] = spuserval.User.Email;
                    entity.Key = spuserval.User.LoginName;
                    entity.Description = spuserval.User.LoginName;
                    entity.DisplayText = spuserval.User.Name;

                    entity = pe.ValidateEntity(entity);
                    entity.IsResolved = true;

                    peoplepickerControlId.Entities.Add(entity);
                }

Monday, 3 August 2015

LINQ to find specific value in column in Datatable c#





DataTable dt;
var foundrows = dt.Select("Column_Heading_Name = 'SomeValue'");
if(foundrows.Length > 0)
{
      //do something
}

Open SharePoint page in modal dialog and return value from modal dialog

To open the page in modal dialog in SharePoint we need to add the following code

On Page Load of the parent page add client click event to the button as follows on Page Load event code behind

btnAdd.OnClientClick = "return OpenModalDialog('" + SPContext.Current.Site.RootWeb.Url + "/SitePages/YourPopupPage.aspx');";

In the ascx page of the parent page add the following script

<script type="text/javascript">

    // function is used to open a page in SharePoint Modal Dialog
    function OpenModalDialog(url) {
        // In order to work with the dialog framework, we need to first create the dialog options
        var options = SP.UI.$create_DialogOptions();
        options.url = url; // URL of the Page
       
        options.showClose = true; // Display Close button
        options.allowMaximize = false; // block maximizing
        options.autoSize = true; // Resize as per page content
        options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback); // Function to capture dialog closed event
        SP.UI.ModalDialog.showModalDialog(options); // Call to open Modal Dialog with above settings
        return false;
    }

    function CloseCallback(result, target) {
        if (result === 1) {
            location.reload(true);
        }
    }

</script>


In the ascx page of the popup page add the following script

<script type="text/javascript">

    function CloseWindow() {
        window.frameElement.commonModalDialogClose(1, 1);
    }

</script>

On button submit click event in server side after applying the logic add the following code at the end

Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", "SP.UI.ModalDialog.commonModalDialogClose(1,1);", true);

On button cancel click event in sercer side add the following code to close the window

this.Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", "SP.UI.ModalDialog.commonModalDialogClose(0, 0);", true);

Grid View buttons not working after Download in SharePoint web part c#

If you are using download button in the GridView and after downloading anything if you are not able to generate any click events on the gridview then add the below code in the Page Load event of the visual web part in SharePoint

string js = @"_spSuppressFormOnSubmitWrapper = true;";
 this.Page.ClientScript.RegisterStartupScript(this.GetType(), "js", js, true);