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:
Simple and 'to the point'. Thanks for this. This very quickly showed me the syntax I needed.
Good on ya.
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!
Post a Comment