How to get innerHTML of a Table in C#

2019-07-04 06:43发布

问题:

 HtmlTable baseCalendar = new HtmlTable();
 HtmlTableRow calendarRow=new HtmlTableRow();
 HtmlTableCell calendarCell = new HtmlTableCell();

 for(int i=0;i<6;i++){
       calendarCell = new HtmlTableCell();

       calendarCell.Controls.Add(new LiteralControl(i.ToString()));
       calendarCell.Style.Add("color", "red");
       calendarRow.Cells.Add(calendarCell);

 }



 string resutlt=baseCalendar.innerHtml.Tostring();

this line say error:HtmlTable' does not support the InnerHtml property?????

回答1:

I hope you want the HTML code for the table you created which cannot be achieved by innerHTML those are valid in case of div, here you should rather use RenderControl something on these lines

StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
baseCalendar.RenderControl(htw)


回答2:

From: http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmltable.innerhtml%28VS.80%29.aspx

Do not read from or assign a value to this property. Otherwise, a System.NotSupportedException exception is thrown. This property is inherited from the HtmlContainerControl class and is not applicable to the HtmlTable class.



回答3:

Here you have to use manually write a Table instead of using HtmlTable

 string str = "<table>";
                for (int i = 0; i < 6; i++)
                {
                    str += "<tr><td style='color:red'>" + i.ToString() + "</td></tr>";
                }
                str += "</table>";
                mainDiv.InnerHtml = str;

And in ASPX page

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

</head>
<body>
    <form id="form1" runat="server">
    <div runat="server" id="mainDiv">
    </div>
    </form>
</body>
</html>


回答4:

A HtmlTable does have the InnerHtml property: http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmltable.aspx

You are missing a caps:

string resutlt=baseCalendar.innerHtml.Tostring(); // note innerHtml -> InnerHtml

However, even though it will compile, you must note that:

Caution

Do not read from or assign a value to this property. Otherwise, a System.NotSupportedException exception is thrown. This property is inherited from the HtmlContainerControl class and is not applicable to the HtmlTable class.