Another way of sending Data from External List to Data View Web Part of Form page of a List

Previously, I told about how you can send Filtered data from an external list to a New/Edit form page’s Data View Web Part by connecting the web parts. Today, I will show another easy way to populate Data within a Data View Web Part sent from a External List.

This time around, I have used Inline Coding inside the Form Page (You have to go in Advanced mode to write inline code and modify the web.config for allowing).

Open up your form page and find the following:

<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">

I have to use my code inside this tag. So, first of all create some Text Fields which will grab the values of the Data sent from the External list.

<asp:TextBox ID="txtID" runat="server" Text="" Visible="false"/>
<asp:TextBox ID="txtFullName" runat="server" Text="" Visible="false"/>
<asp:TextBox ID="txtEmail" runat="server" Text="" Visible="false"/>
<asp:TextBox ID="txtPhone" runat="server" Text="" Visible="false"/>

Note that, I set the visibility to false as obviously you don’t want to show these on your Forms

For writing C# code inside the form, we have to add a tag like the following:

<script runat="server" type="text/c#">

Now, I need to write the logic inside the Page_Load event as that is when my External List will interact with this form and populate the fields.

protected void Page_Load(object sender, EventArgs e)
       //Get the current site
         SPWeb currentWeb = SPContext.Current.Web;
       //Get the current user
         SPUser currentUser = currentWeb.CurrentUser;
        //Get the current user's login name
              string username1 = currentWeb.CurrentUser.LoginName.ToString();
      //As current username's format is ABC\username, i need to use substring to get "username"
             string username2 = username1.Remove(0,4); 

      //This username exist in the external List as Upper Case
             string currentUsername=username2.ToUpper(); 
      //Elevate the permission of current user to use System Account
                    using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                        using (SPWeb web = site.OpenWeb())
                        //Get the List of this current form page, in my case it is "Request For Change"
                         SPList list1 = web.Lists["Request For Change"];  
                            bool isMember=false;
                          //Checking the current user whether he belongs to a particular group
                            isMember=SPContext.Current.Web.IsCurrentUserMemberOfGroup(web.Groups["Request For Change Members"].ID);
                            bool isModerator=false;
                            isModerator=SPContext.Current.Web.IsCurrentUserMemberOfGroup(web.Groups["Request For Change Moderators"].ID);
                            bool isAdmin=false;
                            isAdmin=SPContext.Current.Web.IsCurrentUserMemberOfGroup(web.Groups["Request For Change Admin"].ID);

                       //If the user does not belong to any group, redirect him to the main home page of the site
                            if(isMember==false && isModerator==false && isAdmin==false)

                  //Get the External List, in my case the name is "eBusinessInfo"      
              SPList list=web.Lists["eBusinessInfo"];
                 //Using CAML
               SPQuery theQuery=new SPQuery();

                            theQuery.ViewFields="<FieldRef Name='ID' /><FieldRef Name='FULL_NAME' /><FieldRef Name='EMAIL' /><FieldRef Name='WORK_PHONE' /><FieldRef Name='USER_NAME' />" ;
                            theQuery.Query = @"<Where>
                                <FieldRef Name='USER_NAME' />
                                <Value Type='Text'>"+ currentUsername +@"</Value>
                            //get the Result of CAML query
                            SPListItemCollection foundItem = list.GetItems(theQuery);
                           //Store the ID, Full Name, Email and Phone inside the TextBox that we created before
                            txtID.Text= foundItem[0]["ID"].ToString();
                            txtFullName.Text = foundItem[0]["FULL_NAME"].ToString();
                            string strEmail= foundItem[0]["EMAIL"].ToString();
                            txtPhone.Text= "";
                            //string strPhone=foundItem[0]["WORK_PHONE"].ToString();
                            if(strEmail != null)
                            txtEmail.Text = foundItem[0]["EMAIL"].ToString();
                            txtEmail.Text= "N/A";



Upto now, I have retrieved the value from the external list using a CAML query and stored the value inside the TextBox Fields. Now, In order to use these values inside my form, I have to find the following web part zone:

<WebPartPages:WebPartZone runat=“server” FrameType=“None” ID=“Main” Title=“loc:Main”><ZoneTemplate>

add the parameters inside this web part zone:
<ParameterBinding Name="paramID" Location="Control(txtID, Text)" DefaultValue=""/> 
<ParameterBinding Name="paramFullName" Location="Control(txtFullName, Text)" DefaultValue=""/>
<ParameterBinding Name="paramEmail" Location="Control(txtEmail, Text)" DefaultValue=""/>
<ParameterBinding Name="paramPhone" Location="Control(txtPhone, Text)" DefaultValue=""/>


Then, add the parameters inside the XSLT right after this web part zone.

<xsl:param name="paramID" />
<xsl:param name="paramFullName" />
<xsl:param name="paramEmail" />
<xsl:param name="paramPhone" />

Now, Instead of using SharePoint:FormField for the desired fields, change those like the following:

<asp:TextBox runat="server" id="ff1{$Pos}" ReadOnly="True" Text="{$paramID}" __designer:bind="{ddwrt:DataBind('i',concat('ff1',$Pos),'Text','TextChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@ID')}"/>

While changing this, do not forget to change “Value” and “ValueChanged” to “Text” and “TextChanged” respectively inside the Tag. That’s it. Now, save the form and see the result!

Hide form fields using JQuery and SharePoint Web Services

There are many occasions when we need to hide certain form fields based on some permission / group settings. Well, there is an easy way of achieving this using a JQuery plugin called “SPServices” which is free to use.

Using this plugin, you can call any in built SharePoint web service, get the value retrieved by the web services and use it in your form easily.

In this example, I have three types of users for a specific list which are “Users”, “Moderators” & “Admin”. I would like to check the current user which group he belongs and based on that I am going to hide/show some fields.

First of all, Download the SPServices plugin from here and then open your form in Advanced Mode using SharePoint Designer 2010 and look for the following line:

<asp:Content ContentPlaceHolderId="PlaceHolderBodyAreaClass" runat="server">

Add the script for SPServices:

<script type="text/javascript" src="http://(YOUR SITE URL)/(SAVED FOLDER FOR SPSERVICES)/jquery.SPServices-0.6.2.min.js"></script>

and add the following code under that

<script type="text/javascript">
    $(document).ready( function ()
                    var isUserOnly = false; //User group member only
            var isModerator= false;
            var isAdmin=false;
                    var MODERATORGROUP = "Moderators"; // SPGroup named “Moderators”
                    var ADMINGROUP = "Admin";  // SPGroup named “Admin”

                      operation: "GetGroupCollectionFromUser", //Calling GetGroupCollectionFromUser.asmx web service
                      userLoginName: $().SPServices.SPGetCurrentUser(), //Calling Current User
                      async: false,
                      completefunc: function(xData, Status)
                                        $(xData.responseXML).find("Groups").each(function() //Retrieving the values from Group method of Web Service
                                             $(this).find("Group").each(function()  //Parsing through all the groups the current user belongs to
                        //Checking whether Current User belongs to Admin Group

                                                  if(($(this).attr("Name").toLowerCase() === ADMINGROUP.toLowerCase()))
                                                    isAdmin = true;
                        //Checking whether Current User belongs to Moderators Group

                          else if(($(this).attr("Name").toLowerCase() === MODERATORGROUP.toLowerCase()))

                        //If Current User does not belong to Moderators or Admin, then definitely a normal user

                   }); // Closing SPServices Method


                        //Hide fields as this user is Not a member of Modeartora or Admin Group

            //Hide Approval field if the current user belongs to Moderators Group


            //Show Comments field if the current user belongs to Mdoerators Group


            //Show both fields if the current user belongs to Admin group


After that save the Form, and check that it works!

How to create Dynamic Column in a List Event Receiver & set the Column Name with a Dynamic Value and set Value of that Column for Current List item?

Few days ago, I was working on a List where the necessity of creating dynamic column raised. Also, the need to initiate the column name inside an event receiver and setting the value of the newly column for the current item were needed. So, I created a custom (demo) List which is named as “DemoProjects”.

I created the following columns:

Title, Description, Comments, RadComments (for checking the event)

I needed the column to be created for an existing List item. So, I created a new item like the following keeping “Comments” and “RadComments” blank.



Now, in order to create the event receiver I created a new project of “Event Receiver” type in Visual Studio 2010.

I set the “ItemUpdated” method to True as I need to create the column while updating the list item.


After that, Visual Studio automatically creates the method name and parameters for ItemUpdated method

 public override void ItemUpdated(SPItemEventProperties properties)

Now, this base.ItemUpdated runs will run for each custom list. In order to attain my objective, I have modified this method to the following: ( I have tried to clarify all the steps by commenting each line of code )

  1. public override void ItemUpdated(SPItemEventProperties properties)
  2.        {
  3.            if (properties.ListTitle == “DemoProjects”)
  4.            {
  5.                string colComments = “”; // Column Display name
  6.                string colCommentsStr = “”;  //  Internal name of the Column name
  7.                string curUser = “”;  // Current user name
  8.                using (SPSite site1 = new SPSite(properties.SiteId)) //Accessing the current site with current user permission
  9.                {
  10.                    using (SPWeb web1 = site1.OpenWeb(properties.RelativeWebUrl))
  11.                    {
  12.                        curUser = web1.CurrentUser.Name.ToString();  // Getting the current user display name
  13.                    }
  14.                }
  15.                SPSecurity.RunWithElevatedPrivileges(delegate()  // To Elevate the permisson of the current user which runs as a system acc to create the list column
  16.                {
  17.                    using (SPSite site = new SPSite(properties.SiteId))
  18.                    {
  19.                        using (SPWeb web = site.OpenWeb(properties.RelativeWebUrl))
  20.                        {
  21.                            EventFiringEnabled = false;   // Disabling the events firing to prevent unnecessary actions
  22.                            web.AllowUnsafeUpdates = true;  // To execute actions which are not permitted by default
  23.                            SPList radList = web.Lists[properties.ListId];  // Getting the current List
  24.                            SPListItem project = web.Lists[properties.ListId].GetItemById(properties.ListItem.ID); // Getting the Current List Item
  25.                            colComments = “Comments: “ + curUser; // Setting the column name with current user name
  26.                            if (!radList.Fields.ContainsField(colComments))
  27.                            {
  28.                                radList.Fields.Add(colComments, SPFieldType.Note, false); // Adding new column in current List
  29.                                radList.Update(); // Updating the current List after adding new column
  30.                                Guid guidViewID = radList.Views[“All Items”].ID; // Getting the Guid for “All items” view of current list
  31.                                SPView vw = radList.GetView(guidViewID);
  32.                                vw.ViewFields.Add(colComments);  // Adding the new column in All items view
  33.                                vw.Update();  // Updating the All items view
  34.                                project.Update(); // Updating the current List item
  35.                                base.ItemUpdated(properties);  // Attaching current event to current list item
  36.                                radList.Update();  // Updating the current list
  37.                            }
  38.                            colCommentsStr = radList.Fields[colComments].InternalName.ToString(); // Getting the internal name of newly created column
  39.                        }
  40.                    }
  41.                });
  42.                using (SPSite site2 = new SPSite(properties.SiteId))  // Again accessing the site with current user permission
  43.                {
  44.                    using (SPWeb web2 = site2.OpenWeb(properties.RelativeWebUrl))
  45.                    {
  46.                        SPListItem project1 = web2.Lists[properties.ListId].GetItemById(properties.ListItem.ID); // Getting current List item
  47.                        project1[colCommentsStr] = project1[“Comments”].ToString(); // Setting current item’s new column’s value to Comments column
  48.                        project1[“RadComments”] = “Done!”; // Settting RadComments column’s value to “Done”
  49.                        project1.Update();   // Updating the current list item
  50.                        web2.AllowUnsafeUpdates = false; // After completing the action setting unsafe updates to false
  51.                    }
  52.                }
  53.            }
  54.            EventFiringEnabled = true;  // Enabling event firing for user interaction
  55.            base.ItemUpdated(properties); // Attaching current event to current list item
  56.        }

Now, after deploying this Event Receiver, I edited the previously created new item.


Notice that, I kept “RadComment” blank and there are currently no other columns in this list except these four. So, what happened when I clicked “Save”.

See the following window:


So, my dynamic column got created now (Comments: Current User name) and the value is also set by the event receiver which made it possible to know who commented the item. Now, if another user edits this item, another “Comment: Username” will be automatically be created and thus I can track all the comments made by the item editors and find out what he commented for that item. That’s pretty cool, isn’t it? Enjoy!!