blog community
WebPart 101

I thought I'd show how to build a simple WebPart with a EditorPart attached. And for the demo's sake, not make it overly complicated. So let's build a WebPart which displays some text, and have a custom editor to change that text. In this post I'll run through the WebPart, next post will be about the editor. For those of you who really haven't a clue what WebParts are all about, follow this link.

It is ofcourse possible to create a UserControl and display that as a WebPart, but that is kinda uncool. Let's build a WebPart custom control, by deriving from WebPart.

public class TextWebPart : WebPart
{
}

Our new WebPart will be a composite control, we'll need to override the CreateChildControls method to build up our control. Since we'll only be showing some text, the use of a Label is in order.

Label _textField;
protected
override void CreateChildControls()
{
    _textField =
new Label();
    _textField.ID =
"displayField";
    Controls.Add(_textField);
    ChildControlsCreated = true;
}

We also need a way to set the text on the label, and expose this so our EditorPart can edit the text in a later stage.

[Personalizable, WebBrowsable]
public string Text
{
   
get
    {
        EnsureChildControls();
       
return _textField.Text;
    }
   
set
    {
        EnsureChildControls();
        _textField.Text=
value;
    }
}

That's all for the WebPart. If you want to be able to edit the text without the use of a custom EditorPart, you can. Just place a PropertyGridEditorPart on the same page as the WebPart and use that editor instead.

(Edit)It is required to call EnsureChildControls inside the text property. Because the ASPX will be parsed and the property can be set in the ASPX's HTML. Which would result in the property being set before the CreateChildControls is called. E.g. The generated code looks a bit like:
    _ctrl = TextWebPart();
    _ctrl.Text = "Test123!";(/Edit)


Posted 25-07-2005 8:25 by Anonymous
Powered by Community Server (Commercial Edition), by Telligent Systems