10

I have a calculated field in a list with this formula:
=CID & " - " & Title

When viewing the list, it might display as: "2 - Big Meeting". When I grab the value from code like so:
myItem["CIDandTitle"]

the value comes back as: "string;#2 - BigMeeting". Is there a "correct" way in sharepoint to extract the value or should i simply split on the semicolon and pound sign?

I am using MOSS2007.

Nathan DeWitt
  • 6,511
  • 8
  • 46
  • 66
Chloraphil
  • 2,719
  • 7
  • 35
  • 44

2 Answers2

16

You have to cast it to an SPCalculatedField:

SPFieldCalculated cf = (SPFieldCalculated)myItem.Fields["CIDandTitle"];
string value = cf.GetFieldValueForEdit(myItem["CIDandTitle"]);

or

string value = cf.GetFieldValueAsText(myItem["CIDandTitle"]);
Nathan DeWitt
  • 6,511
  • 8
  • 46
  • 66
  • That works; as does cf.GetFieldValueAsText(myItem["CIDandTitle"]). This approach seems clunky though. – Chloraphil May 22 '09 at 15:07
  • 4
    I had issues trying to get a float this way. I used myItem.GetFormattedValue("floatValue"); – bryanbcook Aug 27 '09 at 14:25
  • I resorted to `myItem.GetFormattedValue("floatValue")` as @bryanbcook suggests because the `.Fields` accessor expects the display name and not the robust internal name. GetFormattedValue does work with internal name! – Swimburger Jan 24 '18 at 18:26
0

The answer given by @Nathan does not specify that you need to provide the display name of the field. It wont work with internalName. Moreover, I'm likely to use as to cast the result.

var cf = list.Fields["calculatedfieldDisplayName"] as  SPFieldCalculated;
String value = cf.GetFieldValueAsText(item["calculatedfieldDisplayName"]);
ameliapond
  • 218
  • 4
  • 18