Adding a custom field type via code

Your custom field type can be added to a list in a browser easily. But how do you add a custom field type via code?

Here is my way:

  1. add a new field with the field type from which your custom field type derived
    • change the field type of the new field to your own custom field type
In my case my custom field type derived from a SPFieldLookup.
 
 1: // create new lookup field 
<pre>&lt;font size=2>&lt;span class=lnum>   2:  &lt;/span>&lt;span class=kwrd>string&lt;/span> newFieldName = fields.AddLookup(&lt;span class=str>"fieldname"&lt;/span>, list.ID, web.ID, &lt;span class=kwrd>false&lt;/span>); &lt;/font></pre><pre class=alt><font size=2><span class=lnum> 3: </span>var newField = fields.GetFieldByInternalName(newFieldName);</font> </pre> 

<pre>&lt;font size=2>&lt;span class=lnum>   4:  &lt;/span>&lt;span class=rem>// change field type to our own &lt;/span>&lt;/font></pre><pre class=alt><font size=2><span class=lnum> 5: </span>newField.SchemaXml = newField.SchemaXml.Replace(<span class=str>"Lookup"</span>, <span class=str>"yourFieldType"</span>);</font></pre> </div> 

 

**Update 4. Feb 2008**

The above solution will bring you a field with the type. But a much smoother way is to create a new field, which has the selected type. This way you don’t need to modify the schema of the field.<div class=csharpcode> <pre class=alt><span class=lnum><font size=2>1: </span>CustomFieldClass field = list.Fields.CreateNewField(<span class=str>"CustomFieldClass"</span>, <span class=str>"The name of the field"</span>);</pre> 

</font>

<pre>&lt;span class=lnum>&lt;font size=2>2:  &lt;/span>list.Fields.Add(field);</pre>

</font></div> 

 <div class=wlWriterEditableSmartContent id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:cdce64aa-cbde-49c7-a43c-69d782ebcc09" style="padding-right:0px;display:inline;padding-left:0px;padding-bottom:0px;margin:0px;padding-top:0px">Technorati Tags: <a href="http://technorati.com/tag/SharePoint" rel=tag>SharePoint</a>,<a href="http://technorati.com/tag/custom+field+type" rel=tag>custom field type</a></div> </div> </div> </div>