Mano Prathibhan C
Mano Prathibhan C

Reputation: 518

Set innerHTML value to a div element from code behind using a string as the div ID

I am using the below code in my .aspx page.

<form runat="server">
  <div style="background:#ffffff;height:1150px;width:100%">
    <center>
      <table class="calendar-table" cellpadding="0" cellspacing="2" border="1">
        <tr>
          <td>
            <div class="cell">
              <div class="cell-day">
                <asp:Label ID="label_day_11" runat="server" Text=""></asp:Label>
              </div>
              <div id="event_11" runat="server">

              </div>
            </div>
          </td>
        </tr>
        <table>
    </center>
  </div>
</form>

In my original code I will have a total of 6 rows and 7 columns and the label rows and columns will go from 11 till 67 in the form of a matrix. Here I would like to set the value of label_day_11 from code behind using C# and for that I am using the below code,

int i = 1; // 1 till 6 rows
int j = 1; // 1 till 7 columns
string dayId = "label_day_" + i.ToString() + j.ToString();
Label day = FindControl(dayId) as Label;
day.Text = "Monday";

The above code works fine. But now I want to assign a innerHTML value to the event_11 div element also. But I am not sure how to get that ID and how to set the innerHTML. Is there any way to access the div control using a string in C# and then set a innerHTML value to it? In case of a asp:Label I used the control value as Label but not sure how to get the control of a normal html div element.

I tried the below code but it does not work for me.

string eventId = "event_" + i.ToString() + j.ToString();
Control div = FindControl(eventId);
StringWriter sw = new StringWriter();
HtmlTextWriter w = new HtmlTextWriter(sw);
div.RenderControl(w);

I am not sure how to proceed using this. Any solutions?

Upvotes: 0

Views: 11365

Answers (1)

Dan Dumitru
Dan Dumitru

Reputation: 5423

I think it should work if you cast it to HtmlGenericControl.

HtmlGenericControl div = FindControl(eventId) as HtmlGenericControl;
div.InnerHtml = "your inner html";

https://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlgenericcontrol(v=vs.110).aspx

Upvotes: 3

Related Questions