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:
- 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
1: // create new lookup field
<pre><font size=2><span class=lnum> 2: </span><span class=kwrd>string</span> newFieldName = fields.AddLookup(<span class=str>"fieldname"</span>, list.ID, web.ID, <span class=kwrd>false</span>); </font></pre><pre class=alt><font size=2><span class=lnum> 3: </span>var newField = fields.GetFieldByInternalName(newFieldName);</font> </pre>
<pre><font size=2><span class=lnum> 4: </span><span class=rem>// change field type to our own </span></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><span class=lnum><font size=2>2: </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>