asp.net render control to string

C#
private string RenderControl()
{
    var sb = new System.Text.StringBuilder();
    using (var stWriter = new System.IO.StringWriter(sb))
    using (var htmlWriter = new HtmlTextWriter(stWriter))
    {
        var p = new Page();
        var ctrl = (YourControl)p.LoadControl("~/controls/building blocks/YourControl.ascx");
        ctrl.Visible = true;

        // do your own init logic if needed

        p.Controls.Add(ctrl);
        ctrl.RenderControl(htmlWriter);
        return sb.ToString();
    }
}
Source

Also in C#: