Friday, December 4, 2009

Add Choice column to list programmatically

Hi All,

Some days back person asked me as a question that you have a post for how to add data in the choice column programmatically however you do not have any article on how to add choice column itself to the list programmatically.

So of course, taking the suggestion positively here is a way you can add choice column programmatically to the list or document library.

Considering lstCustomList is your list object and you have set AllowUnsafeUpdate() to true for the web object. We are adding two choices in the choice column.

First we will add choice column itself to the list and then we will add the choices in that column and update the field. The main point to taken in to consideration is that it is SPFieldChoice not the SPField.

lstCustomList.Fields.Add("ABC", SPFieldType.Choice, false);
lstCustomList.Update();
SPFieldChoice objChoiceCol = (SPFieldChoice)lstCustomList.Fields["ABC"];
string[] strdata = new string[2];
strdata[0] = "Open";
strdata[1] = "Close";
objChoiceCol.Choices.Add(strdata[0]);
objChoiceCol.Choices.Add(strdata[1]);
objChoiceCol.Update();
lstCustomList.Update();


That is it. Your job is done.

2 comments:

Adam Collings said...

Simple and 'to the point'. Thanks for this. This very quickly showed me the syntax I needed.
Good on ya.

Adam Collings said...

Thank you for this.
I was surprised at how important it is that you create the field, add it to the list, update the list and then, get a reference back to the field by name.

I was doing this in a slightly different order. I stored away an object reference to the newly created field at the time of creation, and then tried to add the list items to it. This gave me the error: "0x80070057"

When I followed the order here in your article it all started working for me.
You just helped me move forward with my project. Thank you!




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