SharePoint Blog – René Hézser

How to use the SharePoint Web Controls

SharePoint brings its own controls, which can be used to display list items. In this article I want to show you how to use them in a Webpart. It took me a while to figure this out, because the documentation is kind of incomplete L

OK. Lets start. First lets find out which SharePoint Web Control belongs to which data type in SharePoint.

 

 

 

 

 

SharePoint Web Control

SharePoint data type

SharePoint Web Control

Single line of text

TextField

Multiple lines of text

 

PlainText

NoteField

Rich Text

RichTextField

Enhanced Rich Text

RichTextField

Choice

 

Dropdown

DropDownChoiceField

Radio Button

RadioButtonChoiceField

Number

NumberField

Currency

CurrencyField

Date and Time

DateTimeField

Lookup

 

Single Item

LookupField

Multiple Items

MultipleLookupField

Yes/No

BooleanField

Person or Group

UserField

Hyperlink or Picture

UrlField

Calculated

UrlField

Business data

 

How do we find which control belongs to the data type? We can simply look up this information on each field:

string siteUrl = "http://sharepoint";
string webUrl = "spscontrols";

using (SPSite site = new SPSite(siteUrl))

{

using (SPWeb web = site.AllWebs[webUrl])

{

SPList list = web.Lists["ControlTest"];

foreach (SPField field in list.Fields)

{

Console.WriteLine(field.Title + " – " + field.FieldRenderingControl);

}

}
}

SPControlMode

You can the controls in different Control Modes:

  • SPControlMode.Edit behaves like in an editform page of a list
  • SPControlMode.Display shows the data without the ability to change the values

Use the Controls

So how do we use these controls? The answer to this question is simple: Just use them like "normal" System.Web Controls.

RichTextField rtf = new RichTextField();
rtf.ID = "MultilineRichText";
rtf.ListId = list.ID;
rtf.ItemId = item.ID;
rtf.FieldName = "MultilineRichText";
rtf.ControlMode = SPControlMode.Edit;
this.Controls.Add(rtf);

In this case the RichTextField shows the content from the "MultilineRichText" field from our list, and our listitem in the Editmode. ID and FieldName are the Displayname from our field. You have to set the List, Item and FieldName for the Control, because usually the SharePoint Controls will use the SPContext content (remember: the controls are used in the editform, newform.. pages of every SharePoint List).

With some lines of code, you can display all fields e.g. from the DefaultView of a SharePoint List:

Table table = new Table();
TableRow row;
TableCell cell;
for (int i = 0; i < list.DefaultView.ViewFields.Count; i++)
{

string fieldName = list.DefaultView.ViewFields[i];
SPField field = list.Fields.GetField(fieldName);

row = new TableRow();
cell = new TableCell();
cell.Text = field.Title;
row.Cells.Add(cell);

cell = new TableCell();

// Add a control from RH.SharePoint.SharePointWebControls
Control cntrl = SharePointWebControls.GetSharePointControls(field, list, item, SPControlMode.Display);
// if the control is null (because it can not be rendered with a SharePoint Control) return
if (cntrl == null) continue;

cell.Controls.Add(cntrl);
row.Cells.Add(cell);

cell = new TableCell();
cell.Controls.Add(SharePointWebControls.GetSharePointControls(field, list, item, SPControlMode.Edit));
row.Controls.Add(cell);
table.Rows.Add(row);

}

this.Controls.Add(table);

Use a generic control

Instead of finding a specific control for each SPField, you can use the BaseFieldControl. The advantage is, that it doesn’t matter which field you want to render. The right control will be used.

 
I have updated my class to use the generic instead of finding the matching Webcontrol. This approach makes it easier to use MOSS controls. You don’t have to distinct between WSS and MOSS controls any more.

You can Download the RH.SharePoint.SharePointWebControls class here.

Update:

I updated my SharePointWebControls.

Update 21. Apr 2008:

I updated my SharePointWebControls. This version includes a seperate file, which handels publishing controls from the Microsoft Office SharePoint Server 2007.

Update 19. Jan 2009:

SharePoint Web Controls to access remote content

Update 22. Feb 2009:

The class not uses a generic control instead of a control for each field type.

112 comments for “How to use the SharePoint Web Controls

  1. 27th June 2007 at 11:56

    I couldn’t add RichTextField control to my webpart, it fails when loading… is it necessary to link this control to specific list? For example, I just wanna have a RichText control to write formatted text, and thats all…

  2. 27th June 2007 at 20:27

    You have to bind the Control to a list. Otherwise it does not know “what to do”.
    What do you want to do with the control if you don’t want to save a listitem?

  3. 29th June 2007 at 13:06

    I just want to change standart “textarea” item to some kind of formatted text editor, so I thought “richtextfield” will help me…

    The situation is: I’m doing simple “sendmail” task on Portal, so user fills out special form, that contains several “inputs”, then this form will be sent to SMTP server, that’s all…

    At first, I’ve made a list, and eventhandler for it (that sends an e-mail). But then, I faced a problem with localization. I couldn’t customize newform.aspx page, so I’ve just developed a webpart…

    is there any other way to add “formatted text editor” to webpart?

    P.S. thank’s for support! my e-mail: azadauly@logycom.kz

  4. 29th June 2007 at 21:27

    I guess you could bind the control to a list, and add a custom button which sends the email. You can read the content of the control without sending it to a (new) listitem.

  5. 17th July 2007 at 21:31

    just want to thank you for this post, I spent a lot of time looking after this solution, but finally!

  6. 18th July 2007 at 21:51

    Thanks for your feedback. This is exactly, why I blog ;-)

  7. 27th July 2007 at 18:04

    I want create a custom newform/editform for a list based on a view. I’ve created a custom listpicker toolpart allowing me to choose the list and view I want to base the form on.
    Now I’d like to render the form using Sharepoint Webcontrols but if the list is not within the same site I get this error:

    System.InvalidOperationException: Operation is not valid due to the current state of the object. at Microsoft.SharePoint.SPFolder.get_ContentTypeOrder() at Microsoft.SharePoint.SPContext.get_ContentTypes() at Microsoft.SharePoint.SPContext.get_ContentType() at Microsoft.SharePoint.SPContext.get_Fields() at Microsoft.SharePoint.WebControls.FormComponent.get_Fields() at Microsoft.SharePoint.WebControls.FieldMetadata.get_Field() at Microsoft.SharePoint.WebControls.BaseFieldControl.Render(HtmlTextWriter output) at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) at …

    I didn’t post the entire error as it seems unnecessary.
    Do you know why I can’t access fields outside the current site?

  8. 28th July 2007 at 13:21

    I never tried to access a list from a different site.
    But since you can specify the listId and the itemId from an element to be used for the controls, I guess accessing a list from another site might not be possible. The web property is readonly.

  9. 31st July 2007 at 11:44

    Hello,

    I am using RH.SharePoint in my project but I have some trouble.
    In my project, I use SmartPart to load my .ascx file. In my .cs file associate with my .ascx, I load my controls like that :

    protected void Page_Load(object sender, EventArgs e)
    {


    SPField MyField = MyItem.Fields[field];

    TableRow ligne = new TableRow();
    ligne.ID = MyField.Title;
    ligne.Width = Unit.Percentage(100);

    // cellule de gauche
    TableCell celluleGauche = new TableCell();
    celluleGauche.Width = Unit.Percentage(20);
    celluleGauche.CssClass = “ms-formlabel”;
    celluleGauche.Text = MyField.Title;
    ligne.Cells.Add(celluleGauche);

    // cellule de droite
    TableCell celluleDroite = new TableCell();
    celluleDroite.Width = Unit.Percentage(100);
    celluleDroite.CssClass = “ms-formbody”;
    //SPControlMode MyControlMode = SPControlMode.Edit;
    Control MyControl = RH.SharePoint.SharePointWebControls.GetSharePointControls(MyField, MyList, MyItem, MyControlMode);
    celluleDroite.Controls.Add(MyControl);

    ligne.Cells.Add(celluleDroite);

    // ajout de la ligne
    MyTable.Rows.Add(ligne);
    }

    But when I try to update my Item by a button_click, I have an error with this message “unexpected error”.
    I think my postback event is the probleme but I don’t know how to solve it.

    Do you know why I have this error or, do you have a sample code where you are using these controls to edit and update an item.

  10. 5th August 2007 at 11:56

    Hi,
    sry that I get back to you so late. I was sick.

    The problem you are experiencing, is because you have 2 controls with the same ID.
    Your table uses the field.Title as ID, as well as my SharePoint Control.
    You could set the table.ID like field.Title+”_Table”; or something like that.

  11. 8th August 2007 at 11:31

    Hi,

    I created forms during a project last autumn with a similar approach, but using the general control “FormField” for all kinds of fields.

    I am now in a new project where I need this kind of functionality, so I tried my old method again. Even though all webcontrols render properly using FormField, they do not all seem to function as intended (for instance, the verify user in people picker does not work).

    Tried your method, and everything seems to be working. Excellent post, thank you!

    I do have one question though, how do you update your listitems? In my last project, my webpart was in the context of the list (EditForm.aspx), so I just used SPContext.Current.ListItem.Update() (the field controls seem to be databound somehow) in my event handler.

    In this project, I am trying to remotely update listitems from my webpart (the webpart is not running in the context of the list). Any idea on how to do this except iterating all fieldcontrols and transfering their new values to the listitem?

  12. 8th August 2007 at 20:09

    >Any idea on how to do this except iterating all fieldcontrols and transfering their new values to the listitem?

    I am afraid no :-( But if you find a way, let me know.

  13. 9th August 2007 at 12:33

    Hi again, thanks for your reply.

    Iterating the fields turned out to be a pretty smooth solution, so I’m sticking with it for now.

    I’ve run into some security issues though. I am creating a webpart which accesses a list that the user doesn’t have permission to access (grabbing items using OM and elevated privileges).

    However, when I load the webpart using an account that does not have access to the list, I am denied access. I’m guessing that the Security framework checks the bound listitem for permissions before rendering the page.

    Any idea on how to solve this issue?

  14. 9th August 2007 at 20:19

    You have to create your SPList… within the elevated method. Otherwise you try to modify an object, where you don’t have access to.

  15. 16th August 2007 at 14:21

    I’ve had this error message when trying to use this from an Application Page:

    Operation is not valid due to the current state of the object

    The List exists at the top-level site.
    If I call this page from the top-level site then it works.
    If I call this page from anywhere else, I get an error message!

    anyone have any ideas?

  16. 20th August 2007 at 11:58

    Hello,

    I’m using your .cs file to create my controls and to retrieve there values.
    But i notice your use the field.title to set the control ID. In my code, I use some field.title like “Date d’analyse” or “Date d’émission” and with your code I have some id problème.
    I suggest your change your code to use the field.id to set the control.ID.

    I modify your .cs like that :
    #region Create SharePoint Controls
    private static Control CreateTextFieldControl(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    TextField tf = new TextField();
    tf.ListId = list.ID;
    tf.ItemId = item.ID;
    tf.FieldName = field.Title;
    tf.ID = “Field_”+field.Id;
    tf.ControlMode = mode;
    return tf;
    }

    private static Control CreateNoteFieldControl(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    NoteField nf = new NoteField();
    nf.ListId = list.ID;
    nf.ItemId = item.ID;
    nf.FieldName = field.Title;
    nf.ID = “Field_” + field.Id;
    nf.ControlMode = mode;
    return nf;
    }

    private static Control CreateRichTextFieldControl(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    RichTextField rtf = new RichTextField();
    rtf.ListId = list.ID;
    rtf.ItemId = item.ID;
    rtf.FieldName = field.Title;
    rtf.ID = “Field_” + field.Id;
    rtf.ControlMode = mode;
    return rtf;
    }

    private static Control CreateDropDownChoiceField(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    DropDownChoiceField ddcf = new DropDownChoiceField();
    ddcf.ListId = list.ID;
    ddcf.ItemId = item.ID;
    ddcf.FieldName = field.Title;
    ddcf.ID = “Field_” + field.Id;
    ddcf.ControlMode = mode;
    return ddcf;
    }

    private static Control CreateRadioButtonChoiceField(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    RadioButtonChoiceField rbcf = new RadioButtonChoiceField();
    rbcf.ListId = list.ID;
    rbcf.ItemId = item.ID;
    rbcf.FieldName = field.Title;
    rbcf.ID = “Field_” + field.Id;
    rbcf.ControlMode = mode;
    return rbcf;
    }

    private static Control CreateNumberFieldControl(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    NumberField nf = new NumberField();
    nf.ListId = list.ID;
    nf.ItemId = item.ID;
    nf.FieldName = field.Title;
    nf.ID = “Field_” + field.Id;
    nf.ControlMode = mode;
    return nf;
    }

    private static Control CreateCurrencyFieldControl(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    CurrencyField cf = new CurrencyField();
    cf.ListId = list.ID;
    cf.ItemId = item.ID;
    cf.FieldName = field.Title;
    cf.ID = “Field_” + field.Id;
    cf.ControlMode = mode;
    return cf;
    }

    private static Control CreateDateTimeFieldControl(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    DateTimeField dtc = new DateTimeField();
    dtc.ListId = list.ID;
    dtc.ItemId = item.ID;
    dtc.FieldName = field.Title;
    // Replace blanks with _ so that the control still works
    dtc.ID = “Field_” + field.Id;
    dtc.ControlMode = mode;
    return dtc;
    }

    private static Control CreateLookupFieldControl(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    LookupField lf = new LookupField();
    lf.ListId = list.ID;
    lf.ItemId = item.ID;
    lf.FieldName = field.Title;
    lf.ID = “Field_” + field.Id;
    lf.ControlMode = mode;
    return lf;
    }

    private static Control CreateMultipleLookupFieldControl(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    MultipleLookupField mlf = new MultipleLookupField();
    mlf.ListId = list.ID;
    mlf.ItemId = item.ID;
    mlf.FieldName = field.Title;
    mlf.ID = “Field_” + field.Id;
    mlf.ControlMode = mode;
    return mlf;
    }

    private static Control CreateBooleanField(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    BooleanField bf = new BooleanField();
    bf.ListId = list.ID;
    bf.ItemId = item.ID;
    bf.FieldName = field.Title;
    bf.ID = “Field_” + field.Id;
    bf.ControlMode = mode;
    return bf;
    }

    private static Control CreateUserFieldControl(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    UserField uf = new UserField();
    uf.ListId = list.ID;
    uf.ItemId = item.ID;
    uf.FieldName = field.Title;
    // Replace blanks/@ with _ so that the control still works
    uf.ID = “Field_” + field.Id;
    uf.ControlMode = mode;
    return uf;
    }

    private static Control CreateUrlFieldControl(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    UrlField urlf = new UrlField();
    urlf.ListId = list.ID;
    urlf.ItemId = item.ID;
    urlf.FieldName = field.Title;
    urlf.ID = “Field_” + field.Id;
    urlf.ControlMode = mode;
    return urlf;
    }

    private static Control CreateComputedFieldCotnrol(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    ComputedField cf = new ComputedField();
    cf.ListId = list.ID;
    cf.ItemId = item.ID;
    cf.FieldName = field.Title;
    cf.ID = “Field_” + field.Id;
    cf.ControlMode = mode;
    return cf;
    }

    private static Control CreateAttachmentsFieldControl(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    AttachmentsField af = new AttachmentsField();
    af.ListId = list.ID;
    af.ItemId = item.ID;
    af.FieldName = field.Title;
    af.ID = “Field_” + field.Id;
    af.ControlMode = mode;
    return af;
    }
    #endregion

    thanks a lot for this article and for the supportof users. I hope this comment is useful for you.

    Krao69

  17. 22nd August 2007 at 19:51

    thx. I will look into this, and update my cs.

  18. 2nd September 2007 at 17:53

    hey
    using ur code (which was very helpful, btw) i somehow cant show the title field, which is a computedfield.
    It just doesnt seem to render
    do yo have any idea what might cause the problem>?
    thank you

  19. 3rd September 2007 at 20:40

    Hi,
    what is your formula for your title field? I did not see the behaviour you mentioned.

  20. 19th September 2007 at 15:27

    Hey ,
    i am very much new to SharePoint.
    Could You Please send me code to displau richtext field,
    and i also want to use DateField, if u have codes plz send me to shar.vikash#gmail.com,
    for this i’ll be thank full of yours

  21. 19th September 2007 at 17:29

    Hi,
    when I am back from my holliday, I will update my control.cs. OK? So look back at this page in October.

    Update:
    I updated my Controls

  22. 2nd October 2007 at 02:55

    My Error is exactly similar to the one posted above..

    System.InvalidOperationException: Operation is not valid due to the current state of the object. at Microsoft.SharePoint.SPFolder.get_ContentTypeOrder() at Microsoft.SharePoint.SPContext.get_ContentTypes() at Microsoft.SharePoint.SPContext.get_ContentType() at Microsoft.SharePoint.SPContext.get_Fields() at Microsoft.SharePoint.WebControls.FormComponent.get_Fields() at Microsoft.SharePoint.WebControls.FieldMetadata.get_Field

    As mentioned in the post above, my list is present in a subsite & I am accessing it from a top level site. However, I have the ListID & the subsiteID to open the required list.

    Once I get the reference to the list & its view, I am doing the same process of iterating through the Fields & creating the controls. Also I am using ElevatedPrivileges to open the site/web/list/view. In display mode it is fine, but edit mode, it throws the above error. In fact it goes through the child controls method but fails after that.

    The way I am updating using a link button that posts back on clicking & I have an event-handler for it. The control is not even going till the event handler. it fails right after execution of CreateChildControls

    Any help is greatly appreciated.

  23. 11th October 2007 at 12:08

    I want to create a web part for adding new records in a list. i want to use sharepoint people picker and sharepoint datetime picker on the web part. using submit button data will be added to a list. How i will achive this.

    any help is appreciated.

  24. 12th October 2007 at 18:47

    I have the exact same problem.

    If you want to modify a list by using this webpart it only works if the list lies on the same “level” as the webpart itself.

    If the list exists on a top-level site and you call this page from a subsite you get this error:

    “Operation is not valid due to the current state of the object”

    Has anyone found a solution for this, or does it simply not work?

    martin w

  25. 12th October 2007 at 20:34

    Take a look at this post and the source associated with it:
    http://www.hezser.de/blog/Lists/Beitraege/Post.aspx?ID=47
    I think you will get an impression on how to “work” with SharePoint Controls.

  26. 6th November 2007 at 23:38

    I am building web parts that address a separate, relational database. I can get SPGridView to address this database and display data, and I could certainly use regular ASP.NET controls for text, button, and so on.

    However, I would like to use Sharepoint controls (such as those you list at the top of this blog entry) as they are linked to the Sharepoint CSS.

    The few attempts I have made so far are all throwing the error “Operation is not valid due to the current state of the object” since I am not tying these controls to a List.

    Is there a DIFFERENT set of Sharepoint controls that are not directly dependent on a Sharepoint List? Or should I simply use regular ASP.NET controls, and attempt to point the CssClass property at items in Core.css?

  27. 7th November 2007 at 18:30

    Hi,
    the name “SharePoint” Controls means, you have to use them in SharePoint Context, with SharePoint data.
    But you can create a dummy list, with the fields you need in the site where you want to Webpart to be. Then create a new SPListItem with SPListItem item = list.Items.Add(). You don’t need to save it later on. Just read the values the user filled in.
    René

  28. 9th November 2007 at 12:31

    Hi ..

    I am using your CS class to generate a custom ASPX page which actually maps to any List Item (passing in the WebUrl, ListID and ItemID through the URL).

    It can them mimick the edit page of the list from anywhere in sharepoint (so you can provide a page from anywhere in SharePoint to edit items anywhere else in SharePoint).

    Everything works just fine .. but the RichTextField control is always returning “

    ” as the Value or Text properties.

    Doesn’t matter how much text I throw into the control .. it always shows blank div tags.

    Any idea why this is ?

    – MKeeper

  29. 9th November 2007 at 19:29

    Hi MKeeper,
    recently I worked again with the controls. And if you create them in “CreateChildControls” and get its values in “OnPreRender”, the RichTextField should work. I don’t know how to do it with an aspx page, and not a Webpart. Sry :-(

  30. 22nd November 2007 at 16:23

    Thank you for this post!
    I created ascx control with DateTimeField. It includes following line:

    It works ok. Bu if I add attribute: DateOnly=”true”, I got System.NullReferenceException. It looks like bug in SharePoint’s object model. Have you any ideas how to work around it?

  31. 25th November 2007 at 11:54

    >Have you any ideas how to work around it?
    Sry. I don’t. But I hope the SP1 will be out soon. Hopefully your problem will be solved than.

  32. 26th November 2007 at 16:38

    Hello all,
    I am new to Sharepoint.
    I create a custom page, where use Field to Control “transformation”. But when I press “Submit” button the entered data does not updates, next time, I open edit page, I get the same old data in controls.

    Do I have to save all that data, by myself? Or there is somesort of automatic data storage?

    If I must update data by myself, maybe you can tell me easiest way how can this be done?

    Thank you for any answer

  33. 26th November 2007 at 19:58

    What is a Field Control “transformation”?
    And yes, you have to save all data, if you use custom controls.
    You could take a look at some of my Webparts to get the feeling for the Controls. You can find them in the download library on the front page.
    René

  34. 27th November 2007 at 11:03

    Thanks René.

    But I still dont understand how can I save data from control?

    There is no “Value” field not in Control, not in SpField?
    If I try to set data through, SPField.FieldRenderingControl.Value. It doesnt work. So where is my problem? Don’t say its in DNA ;)
    But I really need to save data from control to SPfield

  35. 20th December 2007 at 14:32

    I associate a datetimefiel controlæ to my pagelayout. I set the Date column to display todays date, but when I edit the new page the date does not appear. Any Idea???

  36. 20th December 2007 at 19:10

    Could you post your code fragment, so I can look at it?

    René

  37. 13th January 2008 at 20:34

    Hi!

    Finally solved the problem of using sharepoint webcontrols from a different site. First of all, we should have the id for the item which we would like to edit or view. The id for the list of the item, the web, where the list exists, and the name of the field.

    First get a proper context for rendering the item:

    SPContext context = SPContext.GetContext(HttpContext.Current, itemId, listId, web);

    Then create the webcontrol and set the appropriate properties.

    TextField control = new TextField();
    control.FieldName = fieldName;
    control.ControlMode = SPContext.Current.FormContext.FormMode;
    control.ListId = listId;
    control.ItemId = itemId;
    control.RenderContext = context;
    control.ItemContext = context;

    I hope, it helps.

  38. 18th January 2008 at 13:27

    Hi!

    I’m having some problem with the UserField control. When I use the control the “Check name” and “Browse” buttons does not work.

    Has anyone had similar experience???

  39. 28th January 2008 at 22:02

    Hi,

    Thx for your post! Awesome!

    Question about the form validation:
    I used your CS class to create my form and added a Button to save the new item. On the Click Event I do SPContext.Current.ListItem.Update(); to update the database. (Work fine)…But how to change the redirection page after that? How to catch TRUE/FALSE on the form validation? How to redirect the user if the update was succesful?

    Thank you!

  40. 21st February 2008 at 17:21

    I had some issues because some of my fields were publishing fields. In my case we only used HTML and Image fields but there are a couple of others listed here:
    http://www.tonstegeman.com/Blog/Lists/Posts/Post.aspx?List=70640fe5%2D28d9%2D464f%2Db1c9%2D91e07c8f7e47&ID=32

    The problem was that publishing fields error on “field.FieldRenderingControl” (publishing fields do not support it) so I had to get around that by using “field.TypeAsString”. It’s a bit of a hack. I also had to add a reference to “Microsoft.SharePoint.Publishing.WebControls”.

    So here is basically how I coded it:
    public static Control GetSharePointControls(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    // check if the field is a buildIn field, or can be rendered by a SharePoint Control
    string fieldType = field.TypeAsString;
    if (fieldType == “HTML” || fieldType == “Image”)
    {
    try
    {
    switch (fieldType)
    {
    case “HTML”:
    return CreateHTMLFieldControl(field, list, item, mode);

    case “Image”:
    return CreateImageFieldControl(field, list, item, mode);
    }
    }
    catch (Exception ex)
    {
    Label lb = new Label();
    lb.ID = “ErrorLabel”;
    lb.Text = string.Format(“Error in GetSharePointControls:
    {0}”, ex);
    return lb;
    }

    }
    else
    {
    if (field.FieldRenderingControl == null || field.Hidden)
    {
    return null;
    }

    try
    {
    switch (field.FieldRenderingControl.ToString())
    {
    case “Microsoft.SharePoint.WebControls.TextField”:
    return CreateTextFieldControl(field, list, item, mode);

    }

    And then I added:

    private static Control CreateHTMLFieldControl(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    RichHtmlField tf = new RichHtmlField();
    tf.ListId = list.ID;
    tf.ItemId = item.ID;
    tf.FieldName = field.Title;
    tf.ID = “Field_” + field.Id;
    tf.ControlMode = mode;
    return tf;
    }

    private static Control CreateImageFieldControl(SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    RichImageField imf = new RichImageField();
    imf.ListId = list.ID;
    imf.ItemId = item.ID;
    imf.FieldName = field.Title;
    imf.ID = “Field_” + field.Id;
    imf.ControlMode = mode;
    return imf;
    }

    Has anyone else found a better solution to this?

    Mike Hatheway

  41. 26th March 2008 at 18:22

    Hi,
    I try to make a custom webpart to add a new event to a calendar list but have problems with the alldayevent and the recurrencefield with your class.
    I get the following error when I check the alldayeventfield or the reccurence in my custom webpart with following stacktrace:

    [NullReferenceException: Object reference not set to an instance of an object.]
    Microsoft.SharePoint.WebControls.RecurrenceField.SetDateTimeFieldProperties() +1138
    Microsoft.SharePoint.WebControls.RecurrenceField.OnLoadComplete(Object sender, EventArgs e) +46
    System.EventHandler.Invoke(Object sender, EventArgs e) +0
    System.Web.UI.Page.OnLoadComplete(EventArgs e) +2063076
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1875

    Is there any field that I have link to these fields or any other solution?

    Thanks in advance

    Ann

    I

  42. 18th April 2008 at 21:23

    Hi,
    I have identified the problem, and will release a new version soon.

    René

  43. 18th April 2008 at 21:34

    Quote:
    Hi,

    Thx for your post! Awesome!

    Question about the form validation:
    I used your CS class to create my form and added a Button to save the new item. On the Click Event I do SPContext.Current.ListItem.Update(); to update the database. (Work fine)…But how to change the redirection page after that? How to catch TRUE/FALSE on the form validation? How to redirect the user if the update was succesful?

    Thank you!
    —————————————————-

    Hi,
    you can redirect using “SPUtility.Redirect”. What do you mean with “catch TRUE/FALSE”? Do you mean if all entries are valid? If so, you can use “Page.IsValid”.

    René

  44. 18th April 2008 at 21:49

    Quote:
    I had some issues because some of my fields were publishing fields. In my case we only used HTML and Image fields but there are a couple of others listed here:
    http://www.tonstegeman.com/Blog/Lists/Posts/Post.aspx?List=70640fe5%2D28d9%2D464f%2Db1c9%2D91e07c8f7e47&ID=32

    The problem was that publishing fields error on “field.FieldRenderingControl” (publishing fields do not support it) so I had to get around that by using “field.TypeAsString”. It’s a bit of a hack. I also had to add a reference to “Microsoft.SharePoint.Publishing.WebControls”.

    ———————————
    Hi Mike,
    I have never thought about publishing fields. I will look into this, thx for your codesample!

    René

  45. 21st April 2008 at 21:22

    Any progress on the userfield control issue or a hint as to what is causing the problem.

    Thanks you and as said before this is awesome.

  46. 21st April 2008 at 21:30

    I am close. The problem was/is that the ID of the control was not set alright. Meaning it was too long. For a quick solution, set the ID to a short value like “FieldUser1″.

    thx
    René

  47. 21st April 2008 at 22:16

    Rene,

    Like I said before thank you so much for this post. I wouldn’t have known where to begin if not for this post. I hope this will help some.

    I changed your code some when I ran into an error with the Multiple lookup field. I changed all the ID’s to be field.Title instead of field.ID. This did not fix the UserField however.

    I have just changed them to field.InternalName and all is working perfectly.

    You are the best.

  48. 1st May 2008 at 18:08

    Hi,

    Thank you for the post.

    Could you please let me know if you resolved the problem of Recurrence control. I am having problem in Calendar list while rendering these contols.

    Thanks,
    Veda

  49. 3rd May 2008 at 14:10

    Hi Veda,
    some fields require interaction between them. e.g. the allday checkbox disables the time from start/end dates.
    I did not figure out how to do this. Maybe later, but don’t expect this to be within the next weeks :-(

    René

  50. 24th July 2008 at 16:30

    Hello,

    as long as I use the Edit mode, everything goes fine.

    When I set mode to Display, I got the default values of each field set at the creation of the list.

    Text and Value, in TextField for example, are empty. I don’t know why, do you have any idea? Thanks.

  51. 24th July 2008 at 17:32

    I don’t get the default value, I got for all type of fields something like :

    [“Column title” column value]

    I don’t know what’s happening.

  52. 24th July 2008 at 20:11

    Hi,
    my guess would be that you did not set the context. Did you set the list, item and field which the control belongs too?

    René

  53. 31st July 2008 at 10:10

    hello,
    actually by using your code for “displaying all the fields”,I gor error saying “The name ‘SharePointWebControls’ does not exist in the current context”.. For that i have add tagprefix ‘SharePointWebControls’ also,but not working properly…
    Plz help…

  54. 31st July 2008 at 20:09

    Thanks René, I solved my last problem “Mode.Display problem”.

    Now I’ve got something more tricky. :)

    I got the DropDownChoiceField and CheckBoxChoiceField Control doesn’t get their data after a postback event.

    I don’t understand why. I will try now with a standard ListBox Control.

    Do you have an idea?

  55. 31st July 2008 at 21:24

    Ok I found the problem for this type of fields!!

    In Moss 2007 version you have to replace all

    case “Microsoft.SharePoint.WebControls.DropDownChoiceField”:
    return ((DropDownChoiceField)returnObject).ItemFieldValue;

    with

    case “Microsoft.SharePoint.WebControls.DropDownChoiceField”:
    return ((DropDownChoiceField)returnObject).Value;

    All the ItemFieldValue used have to be replace by Value propertie in the method GetValueFromObject, because ItemFieldValue propertie give back everytime and only the first available choise of the choice list, and not the choice made by the user…

    And it work fine. It’s was not working for checkbox too, and now it’s working. I didn’t really test the other types who use ItemFieldValue propeertie, but I think it’s the same problem.

  56. 1st August 2008 at 02:56

    foreach splistitem item in list.items…
    always returns me the first item repeated for the numer of items in the list, so if a list has 5 items i see the first item repeated 5 times

    Any clues?

  57. 3rd August 2008 at 23:29

    Well there you have it my RTF renders only as a TF.

    What really baffles me is the fact that the height and width oof the control when it render does match that of the rtf, just without any of the rtf ajax

  58. 4th August 2008 at 14:02

    By using your code, I am able to display proper controls as per the datatypes of fields in the sharepoint list…

    But while displaying richtextbox, it displyas like normal multilne textbox without “Formatting Options”.. So what i need to do for displaying Formatting Options with richtextbox…

    Thanx in advance

    nils…

  59. 2nd September 2008 at 01:35

    Hi,
    I have the same probleme:
    on the default.aspx page, all mode works, but on others pages, the display mode don’t work, and render [“Column Title” column value] instead of the field value.

    Some ideas ??

    Thanks

    Bob

    —————————————————————–
    RE :Correcting of my post

    I don’t get the default value, I got for all type of fields something like :

    [“Column title” column value]

    I don’t know what’s happening.
    um 24.07.2008 15:32

  60. 18th September 2008 at 21:22

    I am trying to set CheckBoxChoiceField with certain values to render out onto page. Any ideas how I can achieve this?

    I have tried setting CheckBoxChoiceField.Value and CheckBoxChoiceField.ItemFieldValue without success. Can you give me an example how I can set these fields with values?

    Thanks

  61. 25th September 2008 at 01:52

    Great Article!

    Can please tell me what should i do if i want to save the changes (in edit mode) back to the list item and if i want to create a new item (in new mode)?

    A code snippet would be helpful.

    thanks!

  62. 28th September 2008 at 17:48

    Hi,

    I am using a RichTextFiled to enter values in to a List. It works fine while adding new Item… but When I tried to populate the RichTextFiled from the List Item it shows blank.

    I am using
    rtf.Text = “stringvalue from the List”;

    Please help.

  63. 10th October 2008 at 21:12

    Is it possible not to specify ListID?
    If I have a site column and a content type containing this column it should be enough for distinguishing what web control to use, it’s default values etc.

    Thx!

  64. 12th October 2008 at 15:28

    Good question. A content type is associated with a list. So I would think, that you have to use a listid.

    René

  65. 28th October 2008 at 14:42

    Hi, using your code which is great, but I cannot make the user field work properly in a Web Part in vs 2008. The lookup icon works, but when you click on the check user icon I get The target ‘ctl00$m$g_eb90ff9d_b5e4_4348_aa17_cccb1b44169e$Field_AssignedTo$ctl00$UserField’ for the callback could not be found or did not implement ICallbackEventHandler.
    I’m trying to write the code to link this up, but I am a little confused about how I get the callback to work. Do you have an example? Thanks

  66. 29th October 2008 at 14:03

    Hi, I’ve found a way around my problem. I have a web part with list boxes on it to choose a content type. When the user changes the content type, I display the content type fields through the ddl_SelectedIndexChanged event. All the fields display correctly,but I get the error with user fields. I’ve got around this by redirecting the current page with a query string to tell it the values posted (rather than view state), and then placing the fields on the screen. Its not ideal but it works! Anyone tell me why?

  67. 31st October 2008 at 18:25

    Usually this kind of problem occurs if not all base methods are called.
    In your Render(Contents), what do you do there. Just render a control which holds your userfield, or base.Render?

    René

  68. 26th November 2008 at 16:05

    Rene, I’m not sure I’m afraid. Because I am using the SharePoint extensions /WebPart, you automatically get base.createchildcontrols . I then just do this.controls.add(control) to add each field to the screen. The variable “control” will be passed back to it from your code based on a list item, and content type field. Its all working now – but I have another query if you might be so kind. I am using exactly the same code to try and read a list in a parent site to the one I am in, and it doesn’t work (works fine on a local list). I get error

    Operation is not valid due to the current state of the object.
    [InvalidOperationException: Operation is not valid due to the current state of the object.]
    Microsoft.SharePoint.SPFolder.get_ContentTypeOrder() +434
    Microsoft.SharePoint.SPContext.get_ContentTypes() +646
    etc etc.

    I can’t see why this doesn’t work as the code works fine if I point at a list in the current site. There must be something else I need to do?. Do you have any ideas? Thanks

  69. 29th November 2008 at 10:10

    Quote:
    Finally solved the problem of using sharepoint webcontrols from a different site. First of all, we should have the id for the item which we would like to edit or view. The id for the list of the item, the web, where the list exists, and the name of the field.

    First get a proper context for rendering the item:

    SPContext context = SPContext.GetContext(HttpContext.Current, itemId, listId, web);

  70. 2nd December 2008 at 18:03

    Rene, thanks for the response, but I am not sure where I should be amending the code to use the context. I guess its somewhere on the control, but I cannot see anything like a spcontext property. Can you confirm what you mean please?

  71. 2nd December 2008 at 20:30

    Just search on this page for SPContext. You will find a comment (13.01.2008 19:34).

  72. 4th December 2008 at 15:39

    Thanks Rene. Thats working now (I also had to add the RenderContext property). However, I have one final thing that you might have seen before? When displaying a read only field, the first one on the page displays the following error :-

    Failed to render “columnname” column because of an error in the “Single line of text” field type control. See details in log. Exception message: There is no Web named “/sitename/default.aspx”..

    If I put the same control on the page twice, the first one errors and the second one displays correctly. Either there is something else I need to do to initiate it first, or there’s a bug in SharePoint – I did see some similar errors relating to hotfix 932621 that has similar symptoms – but I am running SP1 (no infrastructure update yet). Any ideas?

  73. 15th December 2008 at 19:19

    Hi Rene, I am having problems with validation and I don’t seem to be able to find why.

    The required fields don’t seem to be recognised as missing by the IsValid functionality, but other validation e.g. text in a number field is working. Have you any idea why? What could I be doing wrong. I’ve had it working intermittently, but I can’t seem to spot what the problem is.

  74. 16th December 2008 at 12:48

    Rene, (and anyone else who sees this) Worked out what my problem was. I was changing the content type at the same time as updating the fields – which means the mandatory validation works on the default content type. Not sure why other validation does work, but must just be a fluke. To make the validation work properly the item has to be the correct content type when you display the fields. I guess this does make some sense after spending ages working this out.

  75. 13th January 2009 at 22:51

    Can you tell me if you have resolved the issues with Recurrence and All Day Event. I am facing the same issues as Ann who posted a comment on um 26.03.2008 17:22
    and Veda who posted a comment on um 01.05.2008 16:08

    Thanks!

  76. 21st January 2009 at 01:10

    Hi,
    I don’t understand the requirement for this code…?

    Why not just use the control that is returned from the FieldRenderingControl property of an SPField object?

    i.e. in your example code at the top:

    Control cntrl = SharePointWebControls.GetSharePointControls(field, list, item, SPControlMode.Display);

    can simply be replaced by:

    Control cntrl = field.FieldRenderingControl;

    Is there something I am missing? This always returns the correct control to use for the field.

    Your article is very enlightening as far as knowing which controls are used when. However I don’t think in real code you should try to guess which control to use if the sharepoint framework already does that for you. (Have I missed something here?).

    Regards,
    Nick G

  77. 21st January 2009 at 18:57

    Hi Nick,
    I guess the question is if I missed something. I will look into this and do some testing.
    Thank you for your comment!

    René

  78. 22nd January 2009 at 07:15

    Hi René.

    fyi – I have just done some limited testing for a web-part I am developing and this seems to work ok (only tested with a limited set of field types).

    Note, you still need to initialise the field as you are doing in your code, but at least you don’t need to know the type. This is what my code looks like:

    Control cntrl = field.FieldRenderingControl;

    cntrl.ID = “Field_” + field.Id.ToString().Replace(‘-‘, ‘_’).Replace(‘+’, ‘_’);
    cntrl.FieldName = field.Title
    cntrl.ItemId = item.ID;
    cntrl.ListId = list.ID;
    cntrl.ControlMode = SPControlMode.Display;

    SPWeb web = SPControl.GetContextWeb(this.Context);
    SPContext context = SPContext.GetContext(Context, item.ID, list.ID, web);
    cntrl.ItemContext = context;
    cntrl.RenderContext = context;

    Hope this is of use…
    Regards,
    Nick G

  79. 9th February 2009 at 17:05

    public static Control CreateMossControl(Type controlType, SPField field, SPList list, SPListItem item, SPControlMode mode)
    {
    object ctrl = Activator.CreateInstance(controlType);
    controlType.InvokeMember(“ListId”, BindingFlags.SetProperty, null, ctrl, new object[] { list.ID });
    controlType.InvokeMember(“ItemId”, BindingFlags.SetProperty, null, ctrl, new object[] { item.ID });
    controlType.InvokeMember(“FieldName”, BindingFlags.SetProperty, null, ctrl, new object[] { field.Title });
    controlType.InvokeMember(“ID”, BindingFlags.SetProperty, null, ctrl, new object[] { “Field_” + field.Id });
    controlType.InvokeMember(“ControlMode”, BindingFlags.SetProperty, null, ctrl, new object[] { mode });

    return ctrl as Control;
    }

  80. 10th March 2009 at 21:17

    Hey dude,

    When form is loaded and input fields are inserted and when i click savebutton it is not saving into my list. Does anyone has a clue?

    Thanks

  81. 11th March 2009 at 20:00

    Hi John,
    assign the values from the controls to your listitem[field], and save the listitem with listitem.Update()

    René

  82. 17th March 2009 at 21:48

    Cant seem to work for anonymous users..
    prompts for authentication..
    could tell me how?

  83. 18th March 2009 at 19:51

    Hi Totoy,
    what exactly does not work for anonymous users?

    René

  84. 23rd March 2009 at 07:57

    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
    using (var systemSite = new SPSite(“http://sample.mysite.dev”))
    {using (var sysWeb = systemSite.OpenWeb())
    {
    SPList list = sysWeb.Lists[“MyList”];
    SPListItem item = list.Items.Add();
    BaseFieldControl webControl = item.Fields[SPBuiltInFieldId.Title].FieldRenderingControl;
    webControl.ListId = item.ParentList.ID;
    webControl.ItemId = item.ID;
    webControl.FieldName = item.Fields[SPBuiltInFieldId.Title].Title;
    webControl.ID = “Field_” + item.Fields[SPBuiltInFieldId.Title].InternalName;
    webControl.ControlMode = SPControlMode.New;
    Controls.Add(webControl);
    }
    }
    });

    thanks for the stuff your bringing in to the community..

    anyway, when I put this code on an anonymous site, it prompts for authentication..
    were you able to make this work anonymously before?
    thanks a lot! :)

  85. 23rd March 2009 at 20:04

    Hi Totoy,
    the context is missing. You do not assign a context to the controls. Since you are opening a new site/web, I guess the controls need to know where they belong to.
    Look at this post: http://www.hezser.de/blog/archive/2009/01/19/sharepoint-web-controls-to-access-remote-content.aspx

    René

  86. 20th May 2009 at 01:05

    Hi Rene

    Thanks for this, it’s just what I needed. I am having a problem with the “Title” field of a list, though. When I try to display the FieldRenderingControl for that field, I always get this error message:

    Unable to cast object of type ‘Microsoft.SharePoint.SPFieldComputed’ to type ‘Microsoft.SharePoint.SPFieldText’.

    I have debugged the code at runtime, and the created control is

    “Microsoft.SharePoint.WebControls.TextField”

    I am using GetFieldByInternalName to ensure I get the text field (Title has some computed fields also, with other internal names, and they are computed fields.)

    Has anyone come across this, and, more importantly, has anyone solved this problem?

    Thanks in advance

  87. 27th May 2009 at 15:50

    Hi guys, I am a beginner in SharePoint development and I am trying to implement a DateTime control on my Association and Initiation forms. However, I get an error when I need to display those forms. Here is the code I use:








    Any suggestions?

    Thanks

  88. 27th May 2009 at 21:17

    Hi Zarko,
    I guess you will need to point the control to the list, item and field it should render.
    Try to set ListID, ItemID, FieldName and possible ControlMode.

    René

  89. 28th May 2009 at 11:08

    Excellent Post! I have got the fields to render on my page, but I missed something that tells me what I need to actually save the data. Could I just add a SaveButton control to the table and set it’s control mode to Edit?

  90. 28th May 2009 at 21:46

    Hi Daniel,
    item[field.ID] = GetSharePointControlValue(Page.Controls, field);
    item.Update();
    This is how it should work. You might get the idea now :-)

    René

  91. 29th May 2009 at 11:01

    The problem seems to be that the GetSharePointControlValue function is failing. I have tried so many control collections but it does not find the controls on the page even though I see them. During debug I notice that it always fails to find the controls and I am not sure why. I did put the table in a panel. I am trying to see if I can loop through the controls collection to see what it does find.

  92. 29th May 2009 at 18:02

    Update: Using the debugger in VS2008 I have found a problem that I can not figure out. I had my controls way down a control tree and have figured out where they are. However, when stepping through the code, it seems that the controls that hold the data are getting assigned a generic ID like “TextField”. This appears to be the reason that it can not find controls to get data from. I am not sure where the code is falling apart. I wrote a little function to loop through the table and there are controls that have the field names as assigned, but they do not seem to have data. If I return the .Value it is blank. If I return the ItemFieldValue it is not the value on the form, but the value from the list. Any thoughts??

  93. 3rd June 2009 at 12:38

    Hey

    When i remove the “Attachments” field from the default view the controls do not render the value in Display mode, they only render [“Coumn Name” Column Value]. It sounds bizarre, but this is what is happening on multiple enviornments. Appreciate if you could help me on this.

  94. 10th June 2009 at 21:18

    Hi Vaibhav,
    it should :-)
    Make sure you have all the references set, so the control “knows” where and what it should do.

    René

  95. 11th June 2009 at 17:07

    Hi Daniel,
    there was a bug in an previous version of my class. Use the latest, and the problem should be gone.

    René

  96. 14th July 2009 at 16:35

    René,

    I was published in my blog an new release of your code. If you have a custom field, when your code try to instantiate it, can’t find the assembly for render and generate an Exception.

    You can include a new funcion for load the assembly before their instantiation.

    The code is:

    private Object loadObject(string assemblyString, string className)
    {
    Object o = null;
    try
    {
    // Try to instantiate the object without load any DLL (if it was loaded early)
    o = Activator.CreateInstance(Type.GetType(className, true, true));
    }
    catch
    {
    try
    {
    // Try again loading the assembly
    Assembly assembly = Assembly.Load(assemblyString);
    o = Activator.CreateInstance(assembly.GetType(className, true, true));
    }
    catch (Exception ex)
    {
    throw new Exception(“There has been a problem when instantiate object ” + className + ” de ” + assemblyString, ex);
    }
    }
    return o;
    } // loadObject

    And the new instantiation sentence:
    BaseFieldControl webControl = (BaseFieldControl)this.loadObject(field.FieldRenderingControl.GetType().Assembly.ToString(), field.FieldRenderingControl.ToString());

  97. ram
    12th August 2009 at 16:47

    Richtextfield displaying data as ‘[“Column Name” column value]’ instaed of field value in display mode.

    Plese help me out

  98. 21st September 2009 at 13:22

    René,

    The validation doesn’t work. In previous comments they say that you have to use de default content type. But when I look at my list, it uses already the “item” content type. Do I have to change this? And where?

    I’m using a custom site column but I don’t think that is the problem.

    Melanie

  99. 3rd October 2009 at 10:29

    Hi,

    I am going insane with this! I did everything as what this post tell but not able to resolve the Display mode problem.

    I want to show fields from two lists into single webpart. Everything works fine in New/Edit mode but in display mode, fields shows [“Column Name” column value]. After adding AttachmentsField control for one list, display mode worked for that particular list only. For second list it still not showing correct values. Please help.

    I am using following code.

    controlMode = SPControlMode.Display;
    SPWeb controWeb = SPControl.GetContextWeb(this.Context);
    SPContext controlContext = SPContext.GetContext(Context, item.ID, list.ID, controWeb);
    SPContext.Current.FormContext.SetFormMode(controlMode, true);
    controlContext.FormContext.SetFormMode(controlMode, true);

    FormField formField = new FormField();
    formField.ControlMode = controlMode;
    formField.FieldName = field.InternalName;
    formField.ListId = list.ID;
    if (controlMode == SPControlMode.Edit || controlMode == SPControlMode.Display)
    formField.ItemId = item.ID;
    formField.ItemContext = controlContext;
    formField.RenderContext = controlContext;

  100. 20th October 2009 at 22:17

    I have a problem when adding control to my web-part.
    I have 2 web-parts in my solution. They used 1 list and change its items. Web-parts get list by url.

    When I deploy second web-part to another site, I can get list item, but I cannot add RichTextField control.

    I have thr following error:

    System.InvalidOperationException: Operation is not valid due to the current state of the object. at Microsoft.SharePoint.SPFolder.get_ContentTypeOrder() at

    If it is impossible to do like this. Is there any solution to edit items from another site???

  101. 10th December 2009 at 23:58

    @Totoy Bato Did you ever get it working with anonymous users? I have the same problem- adding the RenderingContext and ItemContext didnt help. Works fine with authenticated users but prompts for login for anon even though anon access is set to everything on the site.

    SPList l_contactList = SPContext.Current.Web.Lists[“Volunteer Contact”];
    SPListItem l_newItem = l_contactList.Items.Add();
    l_newItem.Update();
    int l_itemID = l_newItem.ID;
    SPContext l_context = SPContext.GetContext(HttpContext.Current, l_itemID, l_contactList.ID, SPContext.Current.Web);

    foreach (SPField l_field in l_contactList.Fields)
    {
    if (Display(l_field))
    {
    TableRow l_row = new TableRow();
    TableCell l_cellLabel = new TableCell();
    TableCell l_cellValue = new TableCell();
    l_cellLabel.Text = l_field.Title;
    BaseFieldControl l_control =
    l_field.FieldRenderingControl;
    if (l_control != null)
    {
    l_control.ListId = l_contactList.ID;
    l_control.ItemId = l_itemID;
    l_control.ControlMode = SPControlMode.Edit;
    l_control.RenderContext = l_context;
    l_control.ItemContext = l_context;

    // //IS COMMENTED OUT>
    l_cellValue.Controls.Add(l_control);

    l_row.Cells.Add(l_cellLabel);
    l_row.Cells.Add(l_cellValue);

    // //LINE ABOVE IS NOT COMMENTED OUT>
    tblDisplay.Rows.Add(l_row);
    }
    }
    }

  102. 15th February 2010 at 14:02

    if i want to add a new folder in another site and i am using the code above but it doesn’t work cause the item is null, so item.ID is also null? so any solution?

  103. 19th August 2010 at 13:25

    Hi,
    Could you please give me an example of the “New” control mode code? I saw you used Edit/Display as the example and I can see there are differences among these modes.

  104. 20th September 2010 at 20:07

    i’ve noticed checkboxes will cause the form to not work for anonymous users, it goes to a login page.

    all other controls are fine.

    if someone know why tickboxes, checkboxes don’t work, i’d love to know.

  105. 12th October 2010 at 05:17

    To answer the August 19 question;

    SPSite site = new SPSite(‘someurl’);
    SPWeb web = site.OpenWeb();
    SPList list = web.Lists[‘somelibraryname’];
    SPContext context = SPContext.GetContext(Context, list.DefaultView.ID, list.ID, web);
    SPListItem item = list.Items.Add();
    CheckBoxChoiceField cbcf = new CheckBoxChoiceField();
    cbcf.ListId = list.ID;
    cbcf.ItemId = item.ID;
    cbcf.FieldName = field.Title;
    cbcf.ID = field.Required ? GenerateRequiredID(field) : GenerateID(field);
    cbcf.ControlMode = SPControlMode.New;
    cbcf.RenderContext = context;
    cbcf.ItemContext = context;
    site.Dispose();
    web.Dispose();

  106. 18th February 2011 at 03:23

    Hello! Just in case, here http://dotnetfollower.com/wordpress/2010/12/sharepoint-get-spcontrolmode-which-is-associated-with-the-current-request/ is described how to get current control mode on aspx-page as earlier as possible.
    Thanks!

  107. 9th May 2011 at 18:25

    Hi René,
    You use these controls form edit and display forms. I’m trying to use them for new items. On postback i’ve getting the following error: “Failed to get value of the ‘DestinationUser’ column from the “UserField” field type control. See details in log. Exception message: Object reference not set to an instance of an object.. at…
    Have you tryed using sharepoint controls for new items?
    Thanks!

  108. 25th May 2011 at 22:40

    Hey João,
    Found the answer here:
    http://codeshape.wordpress.com/2010/09/29/using-fieldrenderingcontrols-in-custom-web-forms/
    For new items set:
    SPContext spContext = SPContext.GetContext(context, item.ParentList.DefaultView.ID, item.ParentList.ID, item.Web);
    spContext.FormContext.FormMode = SPControlMode.New;

  109. Tom
    18th November 2011 at 12:58

    Hi,

    What ever I try in DisplayMode it always repeats the first item.

    If I turn it to EditMode it displays fine!

    Even in DisplayMode the ItemFieldValue property has the correct value but the rendered HTML always comes out wrong!

    Any clues?

  110. 2nd April 2013 at 14:59

    Hi,

    Was anyone able to figure out the issue in Display Mode. Even i am getting the same issue where it repeats the first item. The ItemFieldValue is proper but the rendered html is always of the first item. Any help is much appreciated.

  111. 17th April 2013 at 10:43

    Hey Guys,
    Hi Bob, Vaibhav, Parwej, ram and somebody who named “Correcting of my post”!!!

    Have you worked out the problem with Display Mode and
    [“Column Title” column value] / [“Column Name” column value] ?

    Cheers,
    Maksym

  112. 7th April 2014 at 16:41

    Hi,

    I am trying to use RichTextField in my visual web part because it provides ribbon functionality to upload documents in the RichTextField control.

    I am able to add it on the webpart but i cannot see the ribbon. please help

Leave a Reply

Your email address will not be published. Required fields are marked *