Tuesday, March 29, 2011

Re ordering lists column in SharePoint programmatically


We all know that re ordering of fields from SharePoint UI is pretty easy. Yes it is. But in this post, we are going to see how we can do the same with the help of code.

It is very simple. Just write down following code and you should be good to go. Before that just have a look at the following list that I have created just to show you the original order of the fields.

Now write down the following code and that will change the order in which we have specified in the array. Do remember that in case the field name has space in between, then you must give _x0020_ as replacement of the space. If you do not give _x0020_ then also it will work without any problem and you will not be able to see these re ordering of fields on the form and then you might wonder why it is not changing? So take care of that.

I've also shown how to make field required.

protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)
using (SPSite site = new SPSite("{site_url}"))
using (SPWeb web = site.OpenWeb())
SPContentType contentType = web.Lists["Reorder Fields Test List"].ContentTypes["Item"];
SPFieldLinkCollection fields = contentType.FieldLinks;

web.AllowUnsafeUpdates = true;

fields.Reorder(new[] { "First_x0020_Name", "Last_x0020_Name", "Blood_x0020_Group", "Title", "Birth_x0020_Date" });
fields["Birth_x0020_Date"].Required = true;

web.AllowUnsafeUpdates = false;

And see the output.

Well one important thing to note here is that this will change the order of fields in the New and Edit form. but it won't change for display form. for that you need to change the view.

1 comment:

Anonymous said...

Awesome! Just what I needed!

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 sharepointkings@gmail.com 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 sharepointkings@gmail.com