How to use the SharePoint Web Controls

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.

116 Comments

Couldn’t

Reply

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…

 

AW: How to use the SharePoint Web Controls

Reply

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?

 

“what to do”

Reply

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

 

AW: How to use the SharePoint Web Controls

Reply

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.

 

thank thank you!

Reply

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

 

You are welcome

Reply

Thanks for your feedback. This is exactly, why I blog 😉

 

Accessing the fields from another site

Reply

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?

 

Hmm.

Reply

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.

 

How to use these controls to edit and update an item ?

Reply

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.

 

Double ID

Reply

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.

 

FormField

Reply

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?

 

Updating

Reply

>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.

 

Security

Reply

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?

 

AW: How to use the SharePoint Web Controls

Reply

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

 

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

Reply

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?

 

Suggestion for your .cs …

Reply

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

 

AW: How to use the SharePoint Web Controls

Reply

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

 

Computed field

Reply

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

 

Formula?

Reply

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

 

Help

Reply

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

 

AW: How to use the SharePoint Web Controls

Reply

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

 

EditMode Error

Reply

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.

 

    Daniel Johnson

    Reply

    Having recently implemented this, I got around it by impersonating the System Account on the sub-site. Something like:

    SPSite temp = new SPSite(“http://yoursubsite.com”);
    SPUserToken adminToken = temp.SystemAccount.UserToken;
    temp.Dispose();

    using (SPSite subsite = new SPSite(“http://yoursubsite.com”, adminToken){
    // your code here
    }

     

How to create new record in list using RH class.

Reply

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.

 

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

Reply

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

 

Re: How to create new record in list using RH class.

Reply

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.

 

Sharepoint controls directed at separate database

Reply

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?

 

Re: Sharepoint controls directed at separate database

Reply

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é

 

RichTextField.Value | RichTextField.Text

Reply

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

 

Re: RichTextField.Value | RichTextField.Text

Reply

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 🙁

 

Bug with DateTimeField

Reply

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?

 

Re: Bug with DateTimeField

Reply

>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.

 

Is data I enter to Control is posted to Field?

Reply

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

 

RE: Is data I enter to Control is posted to Field?

Reply

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é

 

RE: RE: Is data I enter to Control is posted to Field?

Reply

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

 

DateTimeField

Reply

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???

 

Re: DateTimeField

Reply

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

René

 

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

Reply

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.

 

Problem with UserField control

Reply

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???

 

Validation?

Reply

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!

 

Publishing Site

Reply

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

 

problem with calendar list

Reply

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

 

UserField Problem

Reply

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

René

 

Redirect

Reply

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é

 

re: Publishing Site

Reply

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é

 

UserField

Reply

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.

 

re: UserField

Reply

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é

 

re: UserField and other errors

Reply

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.

 

Recurrence Field Problem

Reply

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

 

AW: How to use the SharePoint Web Controls

Reply

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é

 

Mode.Display problem

Reply

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.

 

Correcting of my post

Reply

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.

 

re: Mode.Display problem

Reply

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é

 

‘SharePointWebControls’ does not exist in current context

Reply

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…

 

Thanks

Reply

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?

 

AW: How to use the SharePoint Web Controls

Reply

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.

 

foreach splistitem item in list.items…

Reply

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?

 

RichTextBox , only renders as regular text box.

Reply

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

 

RichTextBox

Reply

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…

 

RE : Correcting of my post

Reply

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

 

Hi René

Reply

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

 

snjY

Reply

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!

 

How to set the value of the RichTextField.

Reply

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.

 

Content Type vs List

Reply

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!

 

re: Content Type vs List

Reply

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

René

 

Using User Fields

Reply

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

 

Re: Using User Fields

Reply

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?

 

re: Using User Fields

Reply

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é

 

AW: How to use the SharePoint Web Controls

Reply

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

 

re: access remote lists

Reply

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);

 

AW: How to use the SharePoint Web Controls

Reply

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?

 

AW: How to use the SharePoint Web Controls

Reply

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

 

AW: How to use the SharePoint Web Controls

Reply

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?

 

Validation again!

Reply

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.

 

RE: Validation Again!

Reply

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.

 

Recurrence Field and AllDayEvent

Reply

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!

 

Why not just use FieldRenderingControl?

Reply

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

 

re: Why not just use FieldRenderingControl?

Reply

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é

 

AW: How to use the SharePoint Web Controls

Reply

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

 

Generic SharePoint control creation wrapper

Reply

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;
}

 

John

Reply

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

 

René Hézser

Reply

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

René

 

Totoy Bato

Reply

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

 

René Hézser

Reply

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

René

 

Totoy Bato

Reply

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! 🙂

 

René Hézser

Reply

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é

 

Bill Saffin

Reply

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

 

Zarko

Reply

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

 

René Hézser

Reply

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é

 

Daniel

Reply

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?

 

René Hézser

Reply

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

René

 

Daniel

Reply

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.

 

Daniel

Reply

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??

 

Vaibhav

Reply

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.

 

René Hézser

Reply

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

René

 

René Hézser

Reply

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

René

 

Pau Codina

Reply

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());

 

ram

Reply

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

Plese help me out

 

Validation

Reply

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

 

Parwej

Reply

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;

 

Dmitriy

Reply

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???

 

stlawrence

Reply

@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;

//
l_cellValue.Controls.Add(l_control);

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

//
tblDisplay.Rows.Add(l_row);
}
}
}

 

ManaleHajj

Reply

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?

 

tomxie

Reply

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.

 

Joss

Reply

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.

 

Adam Macaulay

Reply

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();

 

Roman

Reply

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!

 

João

Reply

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!

 

Chuck

Reply

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;

 

Tom

Reply

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?

 

Venky

Reply

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.

 

Maksym

Reply

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

 

Chandrakanth

Reply

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

 

SharePointWrestler

Reply

Thank you so much. This is exactly what I needed!

 

Sana

Reply

How can I add the new column in my page??

 

Adding SPFields to Web aprt | Learn with Shreedevi…

Reply

[…] Creation of SharePoint fields on webpart […]

 

Leave a Reply to RichTextBox , only renders as regular text box. Cancel reply