views:

1258

answers:

2

A third-party's webcontrol generates the following code to display itself:

<div id="uwg">
    <input type="checkbox" />
    <div>blah-blah-blah</div>
    <input type="checkbox" />
</div>

Is it possible to change it to

<div id="uwg">
    <input type="checkbox" disabled checked />
    <div>blah-blah-blah</div>
    <input type="checkbox" disabled checked />
</div>

When we click on

<asp:CheckBox id="chk_CheckAll" runat="server" AutoPostBack="true" />

located on the same page?

We need to do it at server side (in ASP.NET).

That third-party's control does not give interface for this, so the only possibility is to work with html output. Which page event should I handle (if any)? Also, is there some equivalent to DOM model, or I need to work with output as string?

+4  A: 

Inherit it and find the controls in the control tree, and set attributes as appropriate.

 protected override void OnPreRender(EventArgs e)
 {
      base.OnPreRender(e);
      (this.Controls[6] as CheckBox).Disabled = true;
 }

Obviously this is fragile if the control will modify its output depending on other properties, or if you upgrade the library; but if you need a workaround, this will work.

Tom Ritter
Great! And, I think, I can get the first div by its id (it has id, although I didn't show it), and find its child elements by type in the way similar to shown above?
Roma
Yes, you can use FindControl("id")
Tom Ritter
Thank you. And can I just implement Page.OnPreRender(EventArgs e) for my current page, without inheriting?
Roma
You could, but that would only affect the control on that page, not other places you want to use it.
Tom Ritter
Tested. Doesn't work, because checkboxes are not run at server. (They do not exist in collection of child controls.)
Roma
+4  A: 

When checkboxes are not run at server or are encapsulated inside the control, we can use the following method:

protected override void Render(HtmlTextWriter writer)
{
    // setup a TextWriter to capture the markup
    TextWriter tw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(tw);

    // render the markup into our surrogate TextWriter
    base.Render(htw);

    // get the captured markup as a string
    string pageSource = tw.ToString();

    string enabledUnchecked = "<input type=\"checkbox\" />";
    string disabledChecked = "<input type=\"checkbox\" disabled checked />";

    // TODO: need replacing ONLY inside a div with id="uwg"
    string updatedPageSource = pageSource;
    if (chk_CheckAll.Checked)
    {
         updatedPageSource = Regex.Replace(pageSource, enabledUnchecked,
                disabledChecked, RegexOptions.IgnoreCase);
    }

    // render the markup into the output stream verbatim
    writer.Write(updatedPageSource);
}

Solution is taken from here.

Roma
This is method either for my page or for webcontrol, inherited from that third-party's control.
Roma