Commonly Required Functions/Snippet - Part One

In this post, we will see the functions or the code snippets, which are very frequently required in SharePoint development.

1) Use JavaScript given below to disable field/column in SharePoint custom list.

Steps

Edit your Web part page/ form => add content editor Web part => copy and paste the code given below => change the field name =>save it => after saving, you will see Contact Number field gets disabled.
  1. <script type="text/javascript">  
  2.     $(document).ready(function() {  
  3.         $("input[title='Contact Number']").attr("readonly""true").css('background-color''#f1f1f1');  
  4.     });  
  5. </script>  
2) Get current user and split login name into two i.e domain and name in C# SharePoint with the code given below.
  1. SPUser user = web.CurrentUser;  
  2. string UserName = user.LoginName;  
  3. str[] name = UserName.Split('\\');  
  4. Label.Text = name[1]  
3) The code given below is used to delete the list items.
  1. SPWeb site = SpContext.Current.Web;  
  2. SPListItemCollection listitems = site.Lists["lstName"].Items;  
  3. for (int i = 0; i < listitems.Count; i++) {  
  4.     SPListItem item = listitems[i];  
  5.     if (Write condition  
  6.         if u have any) {  
  7.         item.Delete(i);  
  8.     }  
  9. }  
4) Get the data of multichoice field of SharePoint custom list into DataTable.
  1. DataTable dt1 = new DataTable();  
  2. SPFieldMultiChoiceValue choices = new SPFieldMultiChoiceValue();  
  3. SPListItemCollection collListItems = list.Items;  
  4. foreach(SPListItem item in collListItems) {  
  5.     choices = new SPFieldMultiChoiceValue(item["Name of Column"].ToString());  
  6. }  
  7. for (int i = 0; i < choices.Count; i++) {  
  8.     dt1.Rows.Add(choices[i], choices[i]);  
  9. }  
5) Using blocks, which is commonly required in all the Web parts.
  1. try {  
  2.     using(SPSite site = new SPSite(SpContext.Current.Site)) {  
  3.         using(SPWeb web = site.OpenWeb()) {  
  4.             // ur code  
  5.         }  
  6.     }  
  7. catch (Exception ex) {} catch (SPException ex1) {}  
6) Bind SharePoint Custom list Title column to dropdown list.

Add the code given below in .ascx file.
  1. <div id="dropdown">  
  2.     <asp:DropDownList ID="ddlv" CssClass="ddl" runat="server"></asp:DropDownList>  
  3. </div>  
Add the code given below in .cx file.
  1. protected void Page_Load(object sender, EventArgs e) {  
  2.     try {  
  3.         using(SPSite site = new SPSite("Server url")) {  
  4.             using(SPWeb web = site.OpenWeb()) {  
  5.                 if (!Page.IsPostBack) {  
  6.                     BindData(web);  
  7.                 }  
  8.             }  
  9.         }  
  10.     } catch (Exception) {}  
  11. }  
  12. public void BindData(SPWeb oweb) {  
  13.     SPList list = oweb.Lists["lstName"];  
  14.     ddlv.DataSource = list.Items;  
  15.     ddlv.DataValueField = "Title";  
  16.     ddlv.DataTextField = "Title";  
  17.     ddlv.DataBind();  
  18. }  
7) Open dialog on click on of button JS and C#
  1. <script>  
  2.     function OpenPreview() {  
  3.         dialogfunction('page url''Preview');  
  4.     }  
  5.   
  6.     function dialogfunction(pageurl, title) {  
  7.         var options = {  
  8.             url: pageurl,  
  9.             title = "Dialog Title";  
  10.             width = 900;  
  11.             height = 500;  
  12.             dialogReturnValueCallback: Function.createDelegate(null, CloseCallback)  
  13.         };  
  14.         SP.SOD.execute('sp.ui.dialog.js''SP.UI.ModalDialog.showModalDialog', options);  
  15.     }  
  16.     }  
  17. </script>  
  18. <asp:Button ID="btnPreview" CssClass="btn" Text="Preview" runat="server" OnClientClick="OpenPreview();" />  
8) Check, if the given string is present in URL or not, using JS.
  1. $(document).ready(function() {  
  2.     if (document.location.href.indexOf('Provide string') > -1) {  
  3.         //do something  
  4.     }  
  5. });  
9) Sometimes in SharePoint, we are not able to access some Web part pages if,
  • We break an inheritance of list and libraries, which are used in the Web part.
  • Used/accessed SharePoint groups in the Web parts.
In this scenario, RunWithElevatedPrivileges also does not work, so it will be better to use the code snippet given below.
  1. SPUserToken susertoken = SPContext.Current.Site.SystemAccount.UserToken;  
  2. SPSite site = new SPSite("web url", susertoken) {  
  3.     // code  
  4. }  
The code given above opens/ access the pages, using SystemAccount credentials.

10) In SharePoint custom list, suppose we have column "emailID" and the user is entering space at the end of an email address and then the code shows an errror. If something goes wrong, then add the script given below on that page, using content editor Web part.
  1. function PreSaveAction() {  
  2.     $("input[title='Email ID']").val($("input[title='Email ID']").val.trim());  
  3.     return true;  
  4. }  
Thanks.