Archive

Kategorien

Links

Andere Blogs




ITaCS GmbH


How to use the SharePoint Web Controls  

Apr 292007

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.

   1:  BaseFieldControl webControl = field.FieldRenderingControl;
   2:  webControl.ListId = list.ID; 
   3:  webControl.ItemId = item.ID; 
   4:  webControl.FieldName = field.Title;
   5:  webControl.ID = GetControlID(field);
   6:  webControl.ControlMode = mode;
 
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.

 
Posted by René Hézser | 114  Comments | Trackback Url  | 1  Links to this post | Bookmark this post with:        
Tags: Development, SharePoint, Web Controls
Technorati Tags: , ,

Links to this post

Pingback from  Daniel Buschke – Blog » Benutzung von Sharepoint Controls  on  7/12/2009  4:43 PM

Comments

commented on  Wednesday, June 27, 2007  9:56 AM  by  Couldn't
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...

commented on  Wednesday, June 27, 2007  6:27 PM  by  AW: How to use the SharePoint Web Controls
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?

commented on  Friday, June 29, 2007  11:06 AM  by  "what to do"
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

commented on  Friday, June 29, 2007  7:27 PM  by  AW: How to use the SharePoint Web Controls
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.

commented on  Tuesday, July 17, 2007  7:31 PM  by  thank thank you!
just want to thank you for this post, I spent a lot of time looking after this solution, but finally!

commented on  Wednesday, July 18, 2007  7:51 PM  by  You are welcome
Thanks for your feedback. This is exactly, why I blog ;-)

commented on  Friday, July 27, 2007  4:03 PM  by  Can this be used for a custom newform?
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?

commented on  Saturday, July 28, 2007  11:21 AM  by  Hmm.
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.

commented on  Tuesday, July 31, 2007  9:44 AM  by  How to use these controls to edit and update an item ?
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.

commented on  Sunday, August 05, 2007  9:56 AM  by  Double ID
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.

commented on  Wednesday, August 08, 2007  9:31 AM  by  FormField
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?


commented on  Wednesday, August 08, 2007  6:09 PM  by  Updating
>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.

commented on  Thursday, August 09, 2007  10:33 AM  by  Security
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?

commented on  Thursday, August 09, 2007  6:19 PM  by  AW: How to use the SharePoint Web Controls
You have to create your SPList... within the elevated method. Otherwise you try to modify an object, where you don't have access to.

commented on  Thursday, August 16, 2007  12:21 PM  by  Operation is not valid due to the current state of the object
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?

commented on  Monday, August 20, 2007  9:58 AM  by  Suggestion for your .cs ...
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

commented on  Wednesday, August 22, 2007  5:51 PM  by  AW: How to use the SharePoint Web Controls
thx. I will look into this, and update my cs.

commented on  Sunday, September 02, 2007  3:53 PM  by  Computed field
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

commented on  Monday, September 03, 2007  6:40 PM  by  Formula?
Hi,
what is your formula for your title field? I did not see the behaviour you mentioned.

commented on  Wednesday, September 19, 2007  1:27 PM  by  Help
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

commented on  Wednesday, September 19, 2007  3:29 PM  by  AW: How to use the SharePoint Web Controls
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

commented on  Tuesday, October 02, 2007  12:55 AM  by  EditMode Error
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.

commented on  Thursday, October 11, 2007  10:08 AM  by  How to create new record in list using RH class.
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.

commented on  Friday, October 12, 2007  4:47 PM  by  Operation is not valid due to the current state of the object!
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

commented on  Friday, October 12, 2007  6:34 PM  by  Re: How to create new record in list using RH class.
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.

commented on  Tuesday, November 06, 2007  10:38 PM  by  Sharepoint controls directed at separate database
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?

commented on  Wednesday, November 07, 2007  5:30 PM  by  Re: Sharepoint controls directed at separate database
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é

commented on  Friday, November 09, 2007  11:31 AM  by  RichTextField.Value | RichTextField.Text
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 "<div></div>" 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


commented on  Friday, November 09, 2007  6:29 PM  by  Re: RichTextField.Value | RichTextField.Text
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 :-(

commented on  Thursday, November 22, 2007  3:23 PM  by  Bug with DateTimeField
Thank you for this post!
I created ascx control with DateTimeField. It includes following line:
<SharePointWebControls:DateTimeField runat="server" id="DateTimeField2" FieldName="Modified" ControlMode="Display"/>
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?

commented on  Sunday, November 25, 2007  10:54 AM  by  Re: Bug with DateTimeField
>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.

commented on  Monday, November 26, 2007  3:38 PM  by  Is data I enter to Control is posted to Field?
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

commented on  Monday, November 26, 2007  6:58 PM  by  RE: Is data I enter to Control is posted to Field?
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é

commented on  Tuesday, November 27, 2007  10:03 AM  by  RE: RE: Is data I enter to Control is posted to Field?
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

commented on  Thursday, December 20, 2007  1:32 PM  by  DateTimeField
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???

commented on  Thursday, December 20, 2007  6:10 PM  by  Re: DateTimeField
Could you post your code fragment, so I can look at it?

René

commented on  Sunday, January 13, 2008  7:34 PM  by  Operation is not valid due to the current state of the object!
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.

commented on  Friday, January 18, 2008  12:27 PM  by  Problem with UserField control
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???

commented on  Monday, January 28, 2008  9:02 PM  by  Validation?
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!

commented on  Thursday, February 21, 2008  4:21 PM  by  Publishing Site
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:<br/>{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

commented on  Wednesday, March 26, 2008  5:22 PM  by  problem with calendar list
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

commented on  Friday, April 18, 2008  7:23 PM  by  UserField Problem
Hi,
I have identified the problem, and will release a new version soon.

René

commented on  Friday, April 18, 2008  7:34 PM  by  Redirect
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é

commented on  Friday, April 18, 2008  7:49 PM  by  re: Publishing Site
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é

commented on  Monday, April 21, 2008  7:22 PM  by  UserField
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.

commented on  Monday, April 21, 2008  7:30 PM  by  re: UserField
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é

commented on  Monday, April 21, 2008  8:16 PM  by  re: UserField and other errors
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.

commented on  Thursday, May 01, 2008  4:08 PM  by  Recurrence Field Problem
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

commented on  Saturday, May 03, 2008  12:10 PM  by  AW: How to use the SharePoint Web Controls
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é

commented on  Thursday, July 24, 2008  2:30 PM  by  Mode.Display problem
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.

commented on  Thursday, July 24, 2008  3:32 PM  by  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.

commented on  Thursday, July 24, 2008  6:11 PM  by  re: Mode.Display problem
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é

commented on  Thursday, July 31, 2008  8:10 AM  by  'SharePointWebControls' does not exist in current context
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...

commented on  Thursday, July 31, 2008  6:09 PM  by  Thanks
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?

commented on  Thursday, July 31, 2008  7:24 PM  by  AW: How to use the SharePoint Web Controls
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.

commented on  Friday, August 01, 2008  12:56 AM  by  foreach splistitem item in list.items...
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?

commented on  Sunday, August 03, 2008  9:29 PM  by  RichTextBox , only renders as regular text box.
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

commented on  Monday, August 04, 2008  12:02 PM  by  RichTextBox
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...

commented on  Monday, September 01, 2008  11:35 PM  by  RE : Correcting of my post
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

commented on  Thursday, September 18, 2008  7:22 PM  by  Hi René
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

commented on  Wednesday, September 24, 2008  11:52 PM  by  snjY
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!


commented on  Sunday, September 28, 2008  3:48 PM  by  How to set the value of the RichTextField.
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.

commented on  Friday, October 10, 2008  7:12 PM  by  Content Type vs List
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!

commented on  Sunday, October 12, 2008  1:28 PM  by  re: Content Type vs List
Good question. A content type is associated with a list. So I would think, that you have to use a listid.

René

commented on  Tuesday, October 28, 2008  1:42 PM  by  Using User Fields
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

commented on  Wednesday, October 29, 2008  1:03 PM  by  Re: Using User Fields
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?

commented on  Friday, October 31, 2008  5:25 PM  by  re: Using User Fields
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é

commented on  Wednesday, November 26, 2008  3:05 PM  by  AW: How to use the SharePoint Web Controls
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


commented on  Saturday, November 29, 2008  9:10 AM  by  re: access remote lists
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);

commented on  Tuesday, December 02, 2008  5:03 PM  by  AW: How to use the SharePoint Web Controls
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?

commented on  Tuesday, December 02, 2008  7:30 PM  by  AW: How to use the SharePoint Web Controls
Just search on this page for SPContext. You will find a comment (13.01.2008 19:34).

commented on  Thursday, December 04, 2008  2:39 PM  by  AW: How to use the SharePoint Web Controls
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?

commented on  Monday, December 15, 2008  6:19 PM  by  Validation again!
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.

commented on  Tuesday, December 16, 2008  11:48 AM  by  RE: Validation Again!
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.

commented on  Tuesday, January 13, 2009  9:48 PM  by  Recurrence Field and AllDayEvent
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!

commented on  Tuesday, January 13, 2009  9:51 PM  by  Recurrence Field and AllDayEvent
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!

commented on  Wednesday, January 21, 2009  12:10 AM  by  Why not just use FieldRenderingControl?
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


commented on  Wednesday, January 21, 2009  5:57 PM  by  re: Why not just use FieldRenderingControl?
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é

commented on  Thursday, January 22, 2009  6:15 AM  by  AW: How to use the SharePoint Web Controls
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

commented on  Thursday, January 22, 2009  6:15 AM  by  AW: How to use the SharePoint Web Controls
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

commented on  Monday, February 09, 2009  4:05 PM  by  Generic SharePoint control creation wrapper
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;
}

commented on  Tuesday, March 10, 2009  8:17 PM  by  John
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

commented on  Wednesday, March 11, 2009  7:00 PM  by  René Hézser
Hi John,
assign the values from the controls to your listitem[field], and save the listitem with listitem.Update()

René

commented on  Tuesday, March 17, 2009  8:48 PM  by  Totoy Bato
Cant seem to work for anonymous users..
prompts for authentication..
could tell me how?

commented on  Wednesday, March 18, 2009  6:51 PM  by  René Hézser
Hi Totoy,
what exactly does not work for anonymous users?

René

commented on  Monday, March 23, 2009  6:57 AM  by  Totoy Bato
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! :)

commented on  Monday, March 23, 2009  7:04 PM  by  René Hézser
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é

commented on  Tuesday, May 19, 2009  11:05 PM  by  Bill Saffin
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

commented on  Wednesday, May 27, 2009  1:50 PM  by  Zarko
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:

<wssuc:InputFormSection Title="Due Date" Description="Izaberite datum do kada se mora zavrsiti task" runat="server">
<template_inputformcontrols>
<wssuc:InputFormControl Runat="server" LabelText="Due Date:">
<Template_Control>
<SharePoint:DateTimeField
id="duedate"

/>

</Template_Control>
</wssuc:InputFormControl>
</template_inputformcontrols>
</wssuc:InputFormSection>

Any suggestions?

Thanks

commented on  Wednesday, May 27, 2009  7:17 PM  by  René Hézser
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é

commented on  Thursday, May 28, 2009  9:08 AM  by  Daniel
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?

commented on  Thursday, May 28, 2009  7:46 PM  by  René Hézser
Hi Daniel,
item[field.ID] = GetSharePointControlValue(Page.Controls, field);
item.Update();
This is how it should work. You might get the idea now :-)

René

commented on  Friday, May 29, 2009  9:01 AM  by  Daniel
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.

commented on  Friday, May 29, 2009  4:02 PM  by  Daniel
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??

commented on  Wednesday, June 03, 2009  10:38 AM  by  Vaibhav
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.

commented on  Wednesday, June 10, 2009  7:18 PM  by  René Hézser
Hi Vaibhav,
it should :-)
Make sure you have all the references set, so the control "knows" where and what it should do.

René

commented on  Thursday, June 11, 2009  3:07 PM  by  René Hézser
Hi Daniel,
there was a bug in an previous version of my class. Use the latest, and the problem should be gone.

René

commented on  Tuesday, July 14, 2009  2:35 PM  by  Pau Codina
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());

commented on  Wednesday, August 12, 2009  2:47 PM  by  ram
Richtextfield displaying data as '["Column Name" column value]' instaed of field value in display mode.

Plese help me out

commented on  Monday, September 21, 2009  11:22 AM  by  Validation
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

commented on  Saturday, October 03, 2009  8:29 AM  by  Parwej
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;

commented on  Tuesday, October 20, 2009  8:17 PM  by  Dmitriy
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???

commented on  Thursday, December 10, 2009  10:58 PM  by  stlawrence
@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;

//<DOES NOT PROMPT FOR AUTH IF THE NEXT LINE
//IS COMMENTED OUT>
l_cellValue.Controls.Add(l_control);

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

//<PROMPTS FOR AUTH ON THE NEXT LINE IF THE
//LINE ABOVE IS NOT COMMENTED OUT>
tblDisplay.Rows.Add(l_row);
}
}
}

commented on  Monday, February 15, 2010  1:02 PM  by  ManaleHajj
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?

commented on  Thursday, August 19, 2010  11:25 AM  by  tomxie
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.

commented on  Monday, September 20, 2010  6:07 PM  by  Joss
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.

commented on  Tuesday, October 12, 2010  3:17 AM  by  Adam Macaulay
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();

commented on  Friday, February 18, 2011  2:23 AM  by  Roman
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!

commented on  Monday, May 09, 2011  4:25 PM  by  João
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!

commented on  Wednesday, May 25, 2011  8:40 PM  by  Chuck
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;


commented on  Friday, November 18, 2011  11:58 AM  by  Tom
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?

commented on  Tuesday, April 02, 2013  12:59 PM  by  Venky
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.

commented on  Wednesday, April 17, 2013  8:43 AM  by  Maksym
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

commented on  Monday, April 07, 2014  2:41 PM  by  Chandrakanth
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

Name *:
URL:
Email:
Kommentar:


CAPTCHA Image Validation