Kai Hartmann
Kai Hartmann

Reputation: 3154

Create an asp server control dynamically in an html string, which is then inserted in an aspx

I am on the server side of an asp.net application. There I have some html source code in a variable called 'HtmlText'. This source code is generated from xml via a xsl transformation, and is resulting in something like this:

<h1>ABC Test KH</h1>
<!--place for the control-->
<table class="tablesorter" id="tablesorter183">
<thead>
<tr>
    <th align="left">Name</th>
    <th align="right">DB</th>
    <th align="right">DB Anteil in Prozent</th>
    <th align="right">ABC</th>
</tr>
</thead>
<tbody>
<tr>
    <td align="left" fieldName="Name">Fabrikam, Inc.</td>
    <td align="right" fieldName="DB">881.378,00 €</td>
    <td align="right" fieldName="DB_Anteil_in_Prozent">29,92</td>
    <td align="right" fieldName="ABC">A</td>
</tr>
</tbody>
</table>

Now this source code is inserted in a aspx-website via the InnerHtml-property. There is a div with id 'book' in that aspx:

book.InnerHtml = HtmlText

This works fine so far.

But now I want to create a dropdown-control in that html, which I can access on server-side. This control should be placed between the h1 and table-tags, where the comment <!--place for the control--> is located.

I know how to create asp-control dynamically and bind an event to that, but this works only if I have the aspx in the first place. I cannot do that to some html-source which exists just in a string at that time.

Is there any way to do what I want, or am I on the wrong track here?

Thanks in advance for any suggestions.

Kind regards, Kai

Upvotes: 0

Views: 1659

Answers (1)

banana
banana

Reputation: 1206

I think the only solution is to create a control that inherits DropDownList, and override its RenderControl method.

Something like this:

public override void RenderControl(HtmlTextWriter writer)
{
      //...
      //Fill in the variable HtmlText content
      //Split it to 2 variables - before and after the control place, and:

      writer.Write(startString);
      base.RenderControl(writer);
      writer.Write(endString);
}

And use this control instead of DropDownList.

EDIT: In a case of several controls, I would use the way suggested here: Render .net controls to string and get events to fire:

Split the string to several strings - the first string - from the beginning to the first control, second string - from the first control to the second control, and so on.

And then insert each of the strings to a new LiteralControl, and add them to the page Like this:

book.Controls.Add(LiteralControl1);
book.Controls.Add(DropDownList1);
book.Controls.Add(LiteralControl2);
book.Controls.Add(Button1);

Upvotes: 1

Related Questions