Extend the simple Webpart

Extend the simple Webpart

Now that we know how to create a simple Webpart, we want to add more functionality to it. Let us start with some Controls.

  1. Declare a Control as class variable
  2. Create it in CreateChildControls
  3. Modify the Control in OnPreRender
  4. Render the Control with its content

Declare a Control

public
class
simpleWebpart:WebPart

{

private
HtmlGenericControl _MyDiv;

CreateChildControls

This method creates the control. After the creation, we will be able to access the control from elsewhere, to modify its properties or its content.

protected
override
void CreateChildControls()

{

base.CreateChildControls();

 

// Create a new instance, and add it to the Controls

_MyDiv = new
HtmlGenericControl("DIV");

Controls.Add(_MyDiv);

}

Modify the Control

After the control exists, we can modify it.

protected
override
void OnPreRender(EventArgs e)

{

    base.OnPreRender(e);

 

_MyDiv.Attributes.Add("style", "padding: 20px; margin: 20px; border-style: groove; background-color: #FFFFFF;");

_MyDiv.InnerHtml = "I like SharePoint";

}

Rendering

Finally we render our controls, so that we actually see what we created. If we forget to do so, the controls will be generated, but not visible.

protected
override
void Render(HtmlTextWriter writer)

{


// Determines whether the server control contains child controls.


// If it does not, it creates child controls.

EnsureChildControls();

 


// Renders the ChildControls

RenderChildren(writer);

}

Leave a Reply