问题
I have added the following content to a WebBrowser control on form Load:
private void Form1_Load(object sender, EventArgs e)
{
addFirst();
}
private void addfirst()
{
string html = "<!DOCTYPE html>";
html += "<html><head><title>NewPage</title>";
html += "<style>";
html += "body {font-family: Verdana, Tahoma, sans-serif; font-size: 12px;} .vtop {vertical-align: top;} table th:nth-child(1) {width: 20%;}";
html += "table th:nth-child(2) {width: 30%;} table th:nth-child(3) {width: 50%;}";
html += "</style>";
html += "</head>";
html += "<body>";
html += "<table border='0' id='tableresult'>";
html += "</table>";
html += "</body></html>";
webbrowse.DocumentText = html;
}
Then on Click event handler of a button I want to create a new tr and two td elements:
var doc = webbrowse.Document;
var elem = doc.GetElementById("tableresult");
var email = elem.DomElement;
var tr = webbrowse.Document.CreateElement("tr");
var td1 = webbrowse.Document.CreateElement("td");
var td2 = webbrowse.Document.CreateElement("td");
tr.AppendChild(td1);
tr.AppendChild(td2);
elem.AppendChild(tr);
But when I check the source in the WeBrowser control, I don't see the new TR or the TDs.
How can I resolve it?
回答1:
It's a bit tricky, but you are almost there.
You need to find tbody element of the table and append the row to that, no matter you have created tbody explicitly or not.
Debug tip: When you right click on WebBrowser control and choose View Source, it shows the initial DocumentText, not the modified one. If you want to see the updated document text, watch webBrowser1.Document.Body.InnerHtml.
Note: According to the documentation, setting DocumentText should be enough; when you set DocumentText, it navigates to about:blank and then loads the document content based on the text which you have set. So all the expected things like creating Document object or raising Navigating, Navigated or DocumentComplete events happen. Following the source code also shows the same.
Example
private void Form1_Load(object sender, EventArgs e)
{
var html = @"
<!DOCTYPE html>
<html>
<head><title>NewPage</title></head>
<body>
<table id=""tableresult"">
<thead>
<th>Column 1</th>
<th>Column 2</th>
</thead>
</table>
</body>
</html>";
webBrowser1.DocumentText = html;
}
private void button1_Click(object sender, EventArgs e)
{
var tr = webBrowser1.Document.CreateElement("tr");
var td1 = webBrowser1.Document.CreateElement("td");
td1.InnerHtml = "value 1";
var td2 = webBrowser1.Document.CreateElement("td");
td2.InnerHtml = "value 2";
tr.AppendChild(td1);
tr.AppendChild(td2);
webBrowser1.Document.GetElementById("tableresult")
.GetElementsByTagName("tbody")[0].AppendChild(tr);
}
来源:https://stackoverflow.com/questions/65292570/how-to-insert-a-new-row-into-a-table-in-a-webbrowser-control