Wednesday, September 30, 2009

Issue with Content Type Required field

Recently while creating a custom content type feature, I realized the fields are coming as Optional even after setting attribute Required = “true”

<FieldRef ID="{3154C55D-956E-4049-831F-39AFF3AB7787}" Name="Patient" Required="true" ShowInDisplayForm="true" ShowInNewForm="false" ShowInEditForm="true" />

After changing the attribute value to TRUE (uppercase), Content type fields worked fine.

<FieldRef ID="{3154C55D-956E-4049-831F-39AFF3AB7787}" Name="Patient" Required="TRUE" ShowInDisplayForm="TRUE" ShowInNewForm="FALSE" ShowInEditForm="TRUE" />

Reading lookup field value from SharePoint List item

While reading a lookup column value, it is observed that value returns contains a number and character # followed by the actual lookup value selected. Spitting or substring the value may not be the right way to extract the actual lookup value.

SharePoint provides a object SPFieldLookupValue to read Id and the Value of referenced list item.

using (SPSite site = new SPSite(“http://localhost”))

{

using(SPWeb web = site.OpenWeb())

{

SPList list = web.Lists[“MyList”];

SPListItem item = list.Items[0];

String strvalue = item[“lookupColumn”];

//this value comprises of number (id) and the lookup value with #.

SPFieldLookupValue lookup = new SPFieldLookupValue(strvalue);

String myLookupValue = lookup.LookupValue;

//lookup.LookupId returns the id for the referenced list item

//reading multi-valued lookup field value
SPFieldLookupValueCollection lookupCollection = new SPFieldLookupValueCollection(strvalue);

List<string> strLookupValues =new List<string>();

foreach( SPFieldLookup lookupItem in lookupCollection)

{

strLookupValues.Add(lookupItem.LookupValue);

Console.Write(lookupItem.LookupValue);

}

}

}