Peter de Bruijn
Peter de Bruijn

Reputation: 822

Parallel.ForEach RenderControl of radiobuttonlist fails

I have a parallel loop generating HTML using the Parallel.ForEach statement. Somewhere in the execution i render the Html of controls using the RenderControl function. All controls render well (Textboxes, dropdownlists, checkboxes etc.) but a radiobuttonlist gives the following error:

This is the function I use to render the HTML

public static string ControlToString(Control control)
{
    var sb = new StringBuilder();
    var sw = new StringWriter(sb);
    var hw = new Html32TextWriter(sw);
    control.RenderControl(hw);
    return sb.ToString();
}

The RenderControl statement throws a null reference exception:

An exception of type 'System.NullReferenceException' occurred in System.Web.dll but was not handled in user code.Additional information: Object reference not set to an instance of an object.

If I use a normal foreach loop, the problem does not occur. This is the code I use to make the instance of the radiobuttonlist:

var listControl new RadioButtonList();
listControl.ID = "FAC_" + searchFacet.Guid;
listControl.Items.Add(new ListItem("Select an item", "-1"));

What am I doing wrong? Why is the radiobutton different from all other controls? I cheched during debugging. No parameters seem to be null.

It seems the missing HttpContext was the problem. I 'solved' it by adding a fake HttpContext:

public static string ControlToString(Control control)
{
    if (HttpContext.Current == null)
    {
        HttpContext.Current = new HttpContext(new HttpRequest(string.Empty, "http://localhost:81/default.aspx", string.Empty), new HttpResponse(null));
    }
    var sb = new StringBuilder();
    var sw = new StringWriter(sb);
    var hw = new Html32TextWriter(sw);
    control.RenderControl(hw);
    return sb.ToString();
}

It is a 'hack', does anyone have a better idea?

Upvotes: 0

Views: 116

Answers (0)

Related Questions