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.

0 comments:




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