Ads

Wednesday, 3 April 2013

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;
contentType.Update();


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.

No comments:

Post a Comment

Ads