Friday, November 9, 2012

Render methods in web parts in SharePoint

Today's blog post cover methods of rendering web parts. There are some methods which you can use to render content of a web part. The first method - override RenderContens  method. This method take HtmlTextWriter as argument. So, you can use it to write to the output any information. This code block illustrate how to do it:
protected override void RenderContents(HtmlTextWriter writer)
{
      writer.Write("Hello world");
}
This method simply put text "Hello world" to the output stream of the web part.
Another way to render web part content - override CreateChildControls:
protected override void CreateChildControls()
{
      var lblHello = new Label {Text = "Hello world"};
      Controls.Add(lblHello);
}
We'll get the same result as a previous one, but using CreateChildControls method. You can use the first method in a very simple scenarios, when there is no need to render complex layout with many controls. The second method fit situation when you must have several controls, but with rather simple logic.
But what if we have several controls, but we want insert this controls in a table or a div html tag? The third method help us - we can use both of RenderContents and CreateChildControls overloads. Standard implementation of RenderContents looks like this:
protected override void RenderContents(HtmlTextWriter writer)
{
    foreach(Control control in Controls)
    {
        control.RenderControl(writer);
    }
}
We can call control.RenderControl method in the required sequence and enclosed controls with addition html tags if required. Here is an example:
[ToolboxItemAttribute(false)]
public class HelloWorldWebPart3 : WebPart
{
    protected TextBox _txtName
    protected Button _btnSave;
 
    protected override void CreateChildControls()
    {
        _txtName = new TextBox();
        _btnSave = new Button {Text = "Save"};
        _btnSave.Click += btnSaveClick;
        Controls.Add(_btnSave);
        Controls.Add(_txtName);
    }
 
    private void btnSaveClick(object sender, EventArgs e)
    {
        //some code here
    }
 
    protected override void RenderContents(HtmlTextWriter writer)
    {
        writer.RenderBeginTag(HtmlTextWriterTag.Div);
        writer.Write("Please, enter your name:");
        _txtName.RenderControl(writer);
        writer.RenderBeginTag(HtmlTextWriterTag.Br);
            writer.RenderEndTag();
        _btnSave.RenderControl(writer);
        writer.RenderEndTag();
    }
}

No comments:

Post a Comment