Friday, August 29, 2008

How to add Hidden Field programmatically in MOSS

Hi All,

Just in the reference of my earlier post add multi line of text programmatically, i come to know about one more thing.

I actually wanted to add one Hidden field in the list which also cannot be seen at the time of UI. we know that there is a property called Hidden that can be set to true and false.

But..but.. just try once, you will get an Error. Just Try this,

String Fieldid = spList.Fields.Add("", SPFieldType.Text, false);
SPField objfield = spList.Fields.GetField(Fieldid );
objfield.Hidden = true;

And, see you will get and Error. The Error is because CanToggleHidden property of the Field is set to false, as a name suggest you cannot toggle the hidden property and that even cannot be set by code using property bag.

so all you need to do is use the same approach as i described in my previous post.
add multi line of text programmatically,

The difference is only this,

list.Fields.AddFieldAsXml("Type=\"Boolean\" Required=\"FALSE\" Name=\"yourfieldname\"
CanToggleHidden=\"TRUE\" Hidden=\"TRUE\"/>");

Here you actually set CanToggleHidden to TRUE and only because of this, you can change the Hidden to True in XML. this is not possible by directly setting the properties.

And then just set the Title Property to display name that you want.

There you go, now you will have the hidden field in your list.

Thursday, August 28, 2008

How to Add Multi Line Text Box Field Programmatically in MOSS?


I found very interesting stuff today. I was in a need to add a Multi Line Text through code.
I started adding it with calling the Fields.Add Method of list object and passing the parameter, but as soon as i started adding the Field, i found that there is no direct way to add it.

I figured it out and come to know that we have to use the XML of the field that we want to add.

XML of the field that we want to add is very simple. all you need to do is just take the list definition with the help of solution generator tool, open the schema.xml of that list and check for the field. here you will get the idea that how can field be added in the list. we need to use the same structure of the field and add it for the code.

Means simply try to add multi line text as a field in the list, take schema.xml and check that field inside schema, you will find one tag of <Field ..../> for the same field. that is it we only need to programmatically set it.

so here is the approach that i took,

String strXMLOfField = "<Field Type='Note' DisplayName='School Name' Required='FALSE' NumLines='20' RichText='FALSE' ";

strXMLOfField += " StaticName='School_Name' Name='School_Name'/>";

SPList objList = Web.Lists["<your_List>"];

Web.AllowUnsafeUpdates = true;

objList.Fields.AddFieldAsXml(strXMLOfField, false, SPAddFieldOptions.Default);


Web.AllowUnsafeUpdates = false;

Now as you can see in XML, we have set every possible properties in that and you will also see the same applied in UI if you open that Field once it gets added in the list.

but..but.. Here is one problem. even you have set all properties right then also Internal Name and Static Name just does not make sense here. It should be School_Name as internal name and School Name as Display Name. What happened is School Name actually works fine but internal name will not come as School_Name which actually should come.

If you consider schema.xml of the list and deploy that list as a feature everything just works fine, but same XML if you add with the help of code, it does not work fine!!!!!!!!!!!!!

so i found the way that you need to tweak the Code. so here is the tweaking part of it.

After Adding the field that its returning string id.

so Modify the XML,

String strXMLOfField = "<Field Type='Note' DisplayName='School_Name' Required='FALSE' NumLines='20' RichText='FALSE' ";

//AT the time of adding Field through code, It actually makes the Static Name in no matter what you have given, it will add space in that which you do not want. so keep StaticName, Display Name, and Name same.

strXMLOfField += " StaticName='School_Name' Name='School_Name'/>";

string strFieldID = objList.Fields.AddFieldAsXml(strXMLOfField, false, SPAddFieldOptions.Default);

SPField objfield = objList.Fields[strFieldID];

//Now update the Display Name

objfield.Title = "School Name";

Here is a complete code to use.

String strXMLOfField = "<Field Type='Note' DisplayName='School_Name' Required='FALSE' NumLines='20' RichText='FALSE' ";

strXMLOfField += " StaticName='School_Name' Name='School_Name'/>";

Web.AllowUnsafeUpdates = true;

string strFieldID = objList.Fields.AddFieldAsXml(strXMLOfField, false, SPAddFieldOptions.Default);

SPField objfield = objList.Fields[strFieldID];

objfield.Title = "School Name";

Web.AllowUnsafeUpdates = false;

so, There you go.. now you have finally added the multi line text field programmatically.

Wednesday, August 27, 2008

How to get currently logged-in user in workflow

Hi All,

you will always have simple requirement whenever you are working with workflow is to find the currently logged-in user.

It is really frustrating that it is easy to find who is the originator of the workflowproperties but you cannot find who is currently logged in user from workflowproperties even you have properties available.

Let me give you the scenario.

I assume that you have WorkflowProperties object.

So if you write ,


you will get everything,

but if you write,


All you get is only system account, even the properties from the name looks like it will return you current logged in user. but it actually doesn't.

so why is it not returning it? what can be the reason.

Reason is Workflow actually does not run in the same session or same context, because workflow is to be hosted and to be called from the application by setting up the connection.

So it can be called up by any other application,office applications or any other source, it cannot be always the MOSS that triggers the workflow, and even if you triggers the Workflow from MOSS environment, it will still return you System Account.

so, how to get the Currently Logged-in User?

Here is a trick that i found.

string ModifiedbyUserName = Convert.ToString(workflowProperties.
Item.GetFormattedValue("Modified By"));

This will give you the person who has modified the item, this helps only at between the worklfow not at the time of start up because at the time of start up, originatorname is the currently logged in name of the user.

Let's say, when you modify the task, then you get the Task Item and check for this property, so you will get the current User.

Here when i have used Item, then Item referce to the Item of the list which is being changed. List can be any list, then above is the way you can get the Current Logged in user.

Again the problem is it returns the entire string representing Id, Name and connected properties.

If you fetch this string and display in the Label, then it will get converted to hyperlink which will take you to the UserDisp.aspx.

so you need to tweak the string. Here is a way to tweak the string.

string[] strChar = { "ID=" };

string[] strChars = ModifiedbyUserName.Split(strChar, StringSplitOptions.None);

Int32 iUserID = Convert.ToInt32(strChars[1].Substring(0, strChars[1].IndexOf("\"")));

string strAssignedTo = string.Empty;

for (int iCnt = 0; iCnt <= workflowProperties.Web.SiteUsers.Count - 1;iCnt++)
if (workflowProperties.Web.SiteUsers[iCnt].ID == iUserID)
strAssignedTo = workflowProperties.Web.SiteUsers[iCnt].Name;

Now you will get the Name of the currently logged in user. you can also get all properties of any user because now you have SiteUser in hand.

Sunday, August 24, 2008

How to get previous value of listitem in ItemUpdating event

Hi All,

We have event handlers assigned to the list. Lets say when item is added or updated we trigger the event and handle the event by writing our custom code.

The problem happens many times when you require to know that what was the previously entered value if you handle the updating event. Getting the earlier value (before modification done i.e before updated called) in updating is possible so that we come to know that what was the previous value and what is the new changed value of list item.

All you need to do is write a simple code mentioned below:

SPListItem item = properties.ListItem;

string strAmounr = string.Empty;

if (item["Amount"] != null)
strAmounr = item["Amount"].ToString();

The above code actually gives you the previous value of the Amount column.

Now let's get the new entered value in Amount column of the list.

string strNewAmount = properties.AfterProperties["Amount"].ToString();

Simple!!!! Now you have new value of Amount too. so just compare them and perform your steps.

That's it. your job is done.

Saturday, August 23, 2008

Issues with Data View webpart programmatically

First of All Special Thanks to Jason Huh for his article
Creating a DataView webpart programmatically

Data view web part is useful in SharePoint for filtering data from particular list according to business logic.

We had successfully created data form view (data view) webpart programmatically with the reference of above site.
But we are facing some problems
1) The XslText property is empty (Major one)
2) Sorting is not working
3) Title Link dropdown is not coming (ECB menu is not coming).
4) Getting JavaScript error on mouseover on title link. (ctx… invalid object)
5) Filtering is not working. ( still not solved and working on that )

Now to solve this problem we found that we need to set some properties for Data view webpart.

The XslText property is empty
Before you start coding you need to understand that data view webpart needs xsl or xsl link property to be set for rendering.

And you have to take xsl from Sharepoint Designer.
We are hoping you must how to take XSL from SharePoint designer.

This error comes when proper xml is not supplied to data view webpart.
The easy way to resolve this is Create XSL file.
Copy all the Content between the tags <XSL> and </XSL> in that file.

Then upload that XSL file in “Style Library/Xsl Style Sheet” Folder. If you do not have style library folder in you document library then activate “Office SharePoint Server Publishing Infrastructure” feature from Site collection feature

In coding give full path of the

dataFormWebPart.XslLink =
"http://sharepointkings/sites/dataviewtestsite/Style Library/XSL Style Sheets/testing.xsl";

If your XSL is correct then surly your XslText is empty error will solved.

Now moving forward to other errors.

Most of all the errors will be solved by setting all the property which had been set by SharePoint designer when we create webpart from it.

Here we go for code.

Please read comment in the code to understand code better.
The code has been manipulated so that someone can understand properly.

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Globalization;

namespace Sharepointkings.CustomWebPart
ToolboxData("<{0}:MyDataFormWebPart runat=server></{0}:MyDataFormWebPart>"),
XmlRoot(Namespace = "Sharepointkings.CustomWebPart")]
public class MyDataFormWebPart : Microsoft.SharePoint.WebPartPages.WebPart
DataFormWebPart dataFormWebPart;
protected override void CreateChildControls()

SPSite siteColl = SPContext.Current.Site;
SPWeb site = SPContext.Current.Web;

using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID))
using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID))
dataFormWebPart =
new DataFormWebPart();
dataFormWebPart.Title = " testing ";
dataFormWebPart.SuppressWebPartChrome = false;
dataFormWebPart.FrameType = FrameType.Default;
dataFormWebPart.DetailLink = “/sites/dataviewtestsite/Lists/testingdata /AllItems.aspx";
dataFormWebPart.ExportControlledProperties = true;
dataFormWebPart.IsVisible = true;
dataFormWebPart.AllowRemove = true;
dataFormWebPart.AllowEdit = true;
dataFormWebPart.FrameState = FrameState.Normal;
dataFormWebPart.AllowConnect = true;
dataFormWebPart.IsIncludedFilter = "";
dataFormWebPart.TitleUrl = " /sites/dataviewtestsite /Lists/testingdata/AllItems.aspx";
dataFormWebPart.ShowWithSampleData = false;
dataFormWebPart.HelpMode = WebPartHelpMode.Modeless;
dataFormWebPart.ExportMode = WebPartExportMode.All;
dataFormWebPart.ViewFlag = "9"; // we don’t why this 9 is for but in SPD it set as 9 you can set accordingly

dataFormWebPart.HelpLink = "";
dataFormWebPart.AllowHide = true;
dataFormWebPart.AllowZoneChange = true;
dataFormWebPart.PartOrder = 1;
dataFormWebPart.UseSQLDataSourcePaging = true;
dataFormWebPart.IsIncluded = true;
dataFormWebPart.NoDefaultStyle = "TRUE";

dataFormWebPart.XslLink =
"http://sharepointkings/sites/dataviewtestsite/Style Library/XSL Style Sheets/testing.xsl";

dataFormWebPart.ParameterBindings = parabindings();
SPList list = ElevatedSite.Lists["testingdata "];
dataFormWebPart.ListName = list.ID.ToString();
string query = string.Empty;
query = @"<Query><Where><Gt><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Gt></Where></Query>";
uint maximumRow = 100;
SPDataSource dataSource = GetDataSource("MyWebPartdataSource", ElevatedSite.Url, list, query, maximumRow);


private string parabindings()
// now this section you have to replace with your parabindings
// you will get this values from SPD just before <XSL> tag
StringBuilder strb = new StringBuilder();
// strb.Append("<ParameterBinding Name=\"PageUrl\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"PagePath\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"HttpHost\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"HttpPath\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"List\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"URL_Display\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"HttpVDir\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"View\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"FilterLink\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"Language\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"dvt_adhocmode\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"dvt_fieldsort\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"dvt_sortfield\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"dvt_sortdir\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"dvt_filterfield\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"dvt_firstrow\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"dvt_p2plinkfields\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"dvt_nextpagedata\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"dvt_sorttype\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"dvt_apos\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"filterParam\" Location=\"Postback;Connection\"/>");
// strb.Append("<ParameterBinding Name=\"ImagesPath\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"ListUrlDir\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"EMail\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"Userid\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"URL_DISPLAY\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"URL_EDIT\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"WebQueryInfo\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"URL_Edit\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"URL_Lookup\" Location=\"Postback;Connection;CAMLVariable\"/>");
// strb.Append("<ParameterBinding Name=\"UserID\" Location=\"CAMLVariable\" DefaultValue=\"CurrentUserName\"/>");
// strb.Append("<ParameterBinding Name=\"Today\" Location=\"CAMLVariable\" DefaultValue=\"CurrentDate\"/>");
// strb.Append("<ParameterBinding Name=\"dvt_filterfields\" Location=\"Postback;Connection\"/>");
// strb.Append("<ParameterBinding Name=\"dvt_partguid\" Location=\"Postback;Connection\"/>");
// strb.Append("<ParameterBinding Name=\"dvt_groupfield\" Location=\"Postback;Connection\"/>");
// strb.Append("<ParameterBinding Name=\"dvt_startposition\" Location=\"Postback\" DefaultValue=\"\"/>");
// strb.Append("</ParameterBindings>");
return strb.ToString();

SPDataSource GetDataSource(string dataSourceId, string webUrl, SPList list, string query, uint maximumRow)
SPDataSource dataSource = new SPDataSource();
dataSource.UseInternalName =
dataSource.ID = dataSourceId;
dataSource.DataSourceMode =
dataSource.List = list;
dataSource.UseInternalName = true;
dataSource.IncludeHidden = true;
dataSource.SelectCommand =
"<View>" + query + "</View>";
Parameter listIdParam = new Parameter("ListID");
listIdParam.DefaultValue = list.ID.ToString(

Parameter maximumRowsParam = new Parameter("MaximumRows");
maximumRowsParam.DefaultValue = maximumRow.ToString();

Parameter StartRowIndex = new Parameter("StartRowIndex");
StartRowIndex.DefaultValue = "0";

Parameter nextpagedata = new Parameter("nextpagedata");
nextpagedata.DefaultValue = "0";

QueryStringParameter rootFolderParam = new QueryStringParameter("RootFolder", "RootFolder");


return dataSource;


filtering is not working and Still we are working for the same.

Thursday, August 21, 2008

Content Query Web Part Error

I get the following error when I try to add a ContentByQuery.webpart in my SharePoint site.
"Unable to display this Web Part. To troubleshoot the problem, open this Web page in a Windows SharePoint Services-compatible HTML editor such as Microsoft Office SharePoint Designer. If the problem persists, contact your Web server administrator."

I wonder about this error because this error is not coming in another web application on the same system.

So I started investigating what should be the problem.

Means while I come to know that content query webpart is also not available in the “Add webpart Dialog”.

Then I came to know that this Content Query webpart is the part of
“Office SharePoint Server Publishing Infrastructure Feature“

So I resolved the error by activating this feature. This feature is rested in site collection feature.

And Content Query webpart is also available in the webpart pool.

Adding PeopleEditor control in webpart

Hi All,

I wonder sometimes how this people editor works, Because once you just place the people editor control in web part and then it automatically synchronize the Active Directory if web application is configured as Windows Authentication or from Profile database if Web application is configured as Form Based Authentication. you do not need to do any programming for that. it is really a wonderful thing and i really liked this approach.

I faced several challenges while implementing this control in web part. The requirement is like this. we are not supposed to use a default web parts provided in NewForm, EditForm and DispForm, so we removed those web part and placed our own data entry web part having many validations and pop up windows and many code related stuff that would not be possible with the default web parts.

So but obvious that i have to use people editor control in my web part and use it for getting users from AD and then to store it in the List. Now, because we use our own web part, we ourselves have to write a logic to insert the data entered in data entry web part in the list. so we have to code for this control as well.

so i do it like this, first i add the Field in the list and select set the column to People or Group and select the show Field property as Name(with Presence).

First add the Directive at the top of the page

<%@ Register TagPrefix="wssawc" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

And now you can add the control for peopleeditor anywhere in your webpart. Just place this tag.

<wssawc:PeopleEditor id="peopleContact"
Height='25px' />

You can set different properties depending upon your requirements.

Once you have done this, add a reference for this control in your supporting cs file for the web part (ASCX control).

Do not forget to add reference for : Microsoft.SharePoint.WebControls

Add this line

PeopleEditor peopleContact;

Add this line to your CreateChildControl method and before Page.IspostBack condition

peopleContact = (PeopleEditor)this.ctrlCategoryUserControl.FindControl("{controlnameinascx}");

And finally at the time of inserting the data in the list, just perform the following steps.

SPUser objUser = SPContext.Current.Web.Users[peopleContact.CommaSeparatedAccounts];
String strUserToInsert = objUser.ID + ";#" + objUser.Name;

This is the way you will get the user, if peopleeditor's Multi Select True Or False, this will require modifying this code a bit only.

This will do the insertion for this.

At the time of displaying or editing the same value in Editform Webpart and DispForm Webpart (Your custom made, not the default one that comes with moss), you have to perform the following steps.

I assume that you have fetched a ListItem record in table and now that value for peopleeditor from the field of that List is stored in "UserToDisplay" variable. I also assume that you have performed the same steps as mentioned above for NewForm.

then, just set the following.

peopleContact.CommaSeparatedAccounts = UserToDisplay;

This will display the same User in peopleeditor control.

That's it. Your job is done.

Tuesday, August 19, 2008

Adding survey list programmatically

Hi All,

We all know the surveys are really very important part of many companies. They take the decision based on the survey and only because of this reason MOSS has come up with this facility. We can create a survey from MOSS GUI.

There is also a way we can create a survey programmatically. I would like to demonstrate this.

Let’s develop a code which creates a survey list and also adds the question to it. I have added only one question. You can add any number of questions you want.

SPListTemplate objTemplate = currentWeb.ListTemplates["Survey"];

Guid objGuid = currentWeb.Lists.Add("ServeyFromCode", "survey", objTemplate);

SPList objSurvey = currentWeb.Lists["ServeyFromCode"];

//Let’s add user for the permission

SPMember objMember = currentWeb.Users[“Domain/UserName”];

objSurvey.Permissions.Add(objMember, SPRights.ManageLists);

StringCollection strQuestions = new StringCollection();

string strQuestion = "What should be the timing for the training?";

strQuestions.Add("10 AM - 12 AM");
strQuestions.Add("3 PM - 5 PM");
strQuestions.Add("7 PM - 9 PM");
strQuestions.Add(" 9PM - 11 PM");

objSurvey.Fields.Add(strQuestion, SPFieldType.Choice, true, false, strQuestions);

objSurvey.AllowMultiResponses = false;


Before you write this code please set AllowunsafeUpdates = true for list as well as for web and then after updating list please set it to false again.

When you add this, you will see one more list being added in your site and you can now use that survey

Friday, August 8, 2008

Starting timer job through coding

Hi All,

May times you require to start a timer job from coding.

First to check about your timer job definitions, you need to go to Central Administration -> Operations->Timer Job Definitions.

You will find all Titles that are timer job definitions. These are the "Name" Property that you can set while coding. You can also see that those denifitions belongs to which web application in Web Application column there and also scheduled Type , At what durations they run.

If you want to start any of the job definition programatically, you first need to know the Content database's GUID.

To Get the GUID of Content Database of your web application , go to the following path,

Central Administration > Application Management > Content Databases.

Here you will find each respective web application's content database. Right click that content database, Click on properties and then you will find DatabaseId - {"SomeString"}.

This String will contain the Encoded character, replace them with Proper character like %2D is actually a - sign.

Once you have GUID. keep it with you, that will be requires at the time of coding.

Now you have code to write :

SPSite site = new

foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)

if (job.Name == "Workflow Auto Cleanup")

//Replace this GUID with your content database GUID



That's it. You have started your job through coding.

Thursday, August 7, 2008

Create custom ListViewWebPart

Hi All,

First of All Special Thanks to


Creating ListViewWebpart programmatically


Basics can be found @ :

These sites and people have helped us in this venture.
We are great full to all those on the internet, who apply their thoughts and provide with such good codes and tips.
We sincerely apologize if we forgot to mention any one over here.

Now to the venture: Custom ListViewWebPart

Recently one of the projects in which we are involved needed to develop a Web Part.
This Web Part had to look same as the OOTB (Out Of The Box) DataView.

The requirment further stated that it should have the Following:

1) Show Data from any List.
2) Show Data from any View applied on the List.
3) Show Data from any List with Dynamic Queries.
4) Show be able to sort,filter,edit,add new item etc on the List.

:) There was a never ending List of requirments that the client gave us.

We Created this Web Part from the Base

he Parameter that Make it Fully Dynamic are in the
Tool Panel --> Miscellaneous

Below are the Images that will give you the exact Picture:

The Source Code of the entire Web Part is here:

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Security.Principal;

namespace Com.SharePointKings.Webparts.Com.SharePointKings.Webparts

public class CustomListViewWebPart : System.Web.UI.WebControls.WebParts.WebPart
#region Variable Declaration
private string strlisttolink = string.Empty;
private string strViewOfSourceList = string.Empty;
private string strQuery = string.Empty;

#region Properties

//Get and Set Property of the Source List
WebDisplayName("List Name"),
WebDescription("Pass the Name of the List")]
//Get and Set Property of the Source List
public string ListToLink
return strlisttolink;
strlisttolink = value;

WebDescription("Pass Name of the View that you will like to apply to the List")]
//Get and Set Property of the Source List
public string ViewOfSourceList
return strViewOfSourceList;
strViewOfSourceList = value;
WebDescription("Pass the Filter Query")]
//Get and Set Property of the Source List
public string FilterQuery
return strQuery;
strQuery = value;


public CustomListViewWebPart()
this.ExportMode = WebPartExportMode.All;

protected override void CreateChildControls()


SPWeb web = SPContext.Current.Web;
SPList list = web.Lists[ListToLink];

ViewToolBar toolbar = new ViewToolBar();

SPContext context = SPContext.GetContext(this.Context, list.Views[ViewOfSourceList].ID, list.ID, SPContext.Current.Web);

toolbar.RenderContext = context;


// Instantiate the web part
ListViewWebPart lvwp = new ListViewWebPart();
lvwp.ListName = list.ID.ToString("B").ToUpper();
lvwp.ViewGuid = list.Views[ViewOfSourceList].

SPView webPartView = web.Lists[ListToLink].Views[ViewOfSourceList];
SPList objList = web.Lists[ListToLink];
webPartView.Query = FilterQuery;

// Remove the Toolbar!
// First Option: Do it throught OOTB.This needs to be done from the VIEW of the Web Part
// Second Option: Do it trhough Coding.This line is required to ensure that all the appropriate internal nodes of the SPView are populated

String temp = webPartView.SchemaXml;
System.Reflection.PropertyInfo ViewProp = lvwp.GetType().GetProperty("View", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
SPView spView = ViewProp.GetValue(lvwp, null) as SPView;
// This forces a refresh of the views internal xml or the node's cild nodes are not populated

PropertyInfo nodeProp = webPartView.GetType().GetProperty("Node", BindingFlags.NonPublic | BindingFlags.Instance);
XmlNode node = nodeProp.GetValue(webPartView, null) as XmlNode;

// Now get the Toolbar node from the view so we can update its type property
XmlNode toolbarNode = node.SelectSingleNode("Toolbar");
if (toolbarNode != null)
toolbarNode.Attributes["Type"].Value = "None";
web.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = false;
//End Remove the Toolbar!

web.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = false;
catch (Exception ex)
Label lbl = new Label();
lbl.Text = "Error occured: ";
lbl.Text += ex.Message;

protected override void Render(HtmlTextWriter writer)

Wednesday, August 6, 2008

Issue with update list with list definition

Recently we are facing problem of updating list created by list definition.
We are using site definition/list definition for SharePoint deployment.

Here is the scenario.

Now after deployment we got a change request, like add a new field in one of the list.
These are the step we followed for the change:
1) Create a column in that list (on developer pc).
2) Generate a schema file for that list (which has newly column added).
3) As we all know we need to change first line of newly created schema
because we have to keep our old feature id, old ID (Guid), old
template type etc…
4) Replace schema file in 12/template/feature/<<your feature folder>>
5) Uninstall / install feature.

This trick works if you create a new list with that definition.
But what we found that for some list this is not working.
In old list we got a problem.
We only have a single column which is “Title” available in new/edit list.
Again if we create a new list with this it works perfectly but if you opens old list then you will get only single title column for insertion and updation.

For resolving this problem, there is one another thing that to be taken care.
There is “<ContentTypes>” tag in schema.xml for list definition
What we have observed is that while taking new definition of List, Content type id is also getting changed.
So that what we had done is keep old contain type id in new schema file.
And bingo…’s working.

Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to