SharePoint Blog - René Hézser

Anmelden  RSS Feed RSS Feed
Startet die Suche

Apr 292007

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.

   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.


Published: 4/29/2007  11:02 AM | 104  Comments | 1  Links to this post
Tagged as: Development, SharePoint, Web Controls

Apr 162007

Page Viewer Webpart with auto adjusting height

Mart Muller wrote a great article about the page viewer Webpart. If you put the JavaScript onto the page which is displayed inside the page viewer Webpart, it will auto adjust its height.

http://blogs.tamtam.nl/mart/SharePointPageViewerAutomaticallyAdjustIFrameHeight.aspx


Published: 4/16/2007  5:45 PM | 0  Comments | 0  Links to this post
Tagged as: SharePoint

Apr 162007

Write a SPFieldUser

If you have a list which contains a SPFieldUser field (with multiple selection), you can add users too it with the following code:

using (SPSite site = new SPSite("http://site"))

{

using (SPWeb web = site.AllWebs["Web"])

    {

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

    SPListItem item = list.Items[0];

    SPFieldUserValueCollection values = (SPFieldUserValueCollection)item["Users"];

    SPUserCollection users = web.AllUsers;

    foreach (SPUser user in users)

    {

        values.Add(new SPFieldUserValue(web, user.ID, user.Name));

    }

    item["Users"] = values;

    item.Update();

    }

}

In this example the list "List" would contain a field with the name "Users", which takes users. All web users are added to the field "Users" of the first list item, which is then updated.


Published: 4/16/2007  5:40 PM | 4  Comments | 0  Links to this post
Tagged as: Development, SharePoint, SPField

Apr 152007

Ajax Webpart displays Webservice data

In this post I want to show how to create an Ajax Webpart, which receives its data from a Webservice – and until the data arrived – shows a status bar.

As base for the Webpart, I took the one from Mark Collins and his great article http://sharethispoint.com/archive/2006/11/15/Build-web-parts-with-ajax.aspx.

The approach is to render the Webpart with only a <DIV>, and let the client – after it finishes querying the Webservice – fill the data into the <DIV> previously created.

The original version from Mark Collins comes without server side controls. I created the <DIV> as a HTMLGenericControl, because I wanted to have more control over it (and I was curious if it worked).

The basic stays the same. Long running operations are moved from your normal Webpart to the RaiseCallbackEvent method.

public string GetCallbackResult()

{

return this._AjaxData;

}

 

public void RaiseCallbackEvent(string eventArgument)

{

this._AjaxData = CalculateContent();

}

The content returned by the CalculateContent Method is a simple string, which the clients renders later into the <DIV> element.

string CalculateContent()

{

string returnString = string.Empty;

 

try

{

TextWriter tw = new StringWriter();

HtmlTextWriter _TxtWriter = new HtmlTextWriter(tw);

 

_Grid = new SPGridView();

_Grid.DataSource = GetGridDataSource();

 

// catch if the grid datasource is empty

if (_DS == null)

{

return "<IMG src=\"/_layouts/images/BROKENLINK.GIF\" border=\"0\"/> no data received";

}

...

_Grid.DataBind();

 

_Grid.RenderControl(_TxtWriter);

returnString = _TxtWriter.InnerWriter.ToString();

}

catch (Exception ex)

{

_ErrorText += "Error in CalculateContent:\r\n:" + ex.ToString() + "\r\n";

returnString = _ErrorText;

}

 

return returnString;

}

This approach has a big disadvantage. You cannot use sorting, paging and filtering in the SPGridView, because it is created on the client side. You can use grouping, though. So what can we do about sorting and paging?

  • Sorting can be realized with a Webpart property, which takes the sort field an order, and sorts the underlying DataSet/DataView.

private if (!String.IsNullOrEmpty(_SortString))

{

string[] sortArray = _SortString.Split(';');

if (sortArray.Length == 2)

{

SortExpression = sortArray[0];

SortDirection = sortArray[1];

if (DataSetContainsField(_DS, SortExpression))

{

_DS.Tables[0].DefaultView.Sort = SortExpression + " " + SortDirection;

}

}

}

  • Filtering is also realized with a Webpart property, and modifying the DataSet/DataView

if (!String.IsNullOrEmpty(_FilterString) && _FilterString.Contains("="))

{

string filterColumnName = _FilterString.Substring(0, _FilterString.IndexOf('='));

 

// catch typos in the filter

if (DataSetContainsField(_DS, filterColumnName))

{

_DS.Tables[0].DefaultView.RowFilter = _FilterString;

}

}

  • Paging: As soon, as I find a better solution, I will tell you about it J

Download the code here.


Published: 4/15/2007  10:56 AM | 1  Comment | 0  Links to this post
Tagged as: Webparts, Development, SharePoint