我有一个#win app程序.我在我的数据库中用html格式保存文本但我想在webbrowser中向我的用户显示它.如何将字符串html内容显示到webbrowser控件中?
提前致谢
i10*_*100 102
试试这个:
webBrowser1.DocumentText =
"<html><body>Please enter your name:<br/>" +
"<input type='text' name='userName'/><br/>" +
"<a href='http://www.microsoft.com'>continue</a>" +
"</body></html>";
Run Code Online (Sandbox Code Playgroud)
m3z*_*m3z 26
正如Thomas W.所评论的那样 - 我几乎错过了这个评论,但我遇到了同样的问题所以我认为值得重写作为答案.
主要问题是在第一次分配webBrowser1.DocumentText到某些html之后,后续分配没有任何效果.
可以在http://weblogs.asp.net/gunnarpeipman/archive/2009/08/15/displaying-custom-html-in-webbrowser-control.aspx上找到由Thomas链接的解决方案,但是我将在下面进行总结以防此页面将来不可用.
简而言之,由于webBrowser控件的工作方式,每次要更改内容时都必须导航到新页面.因此,作者提出了一种更新控件的方法:
private void DisplayHtml(string html)
{
webBrowser1.Navigate("about:blank");
if (webBrowser1.Document != null)
{
webBrowser1.Document.Write(string.Empty);
}
webBrowser1.DocumentText = html;
}
Run Code Online (Sandbox Code Playgroud)
但是我发现在我当前的应用程序中,我从行中获得了一个CastException if(webBrowser1.Document != null).我不知道为什么会这样,但是我发现如果我把整个if块包裹在试试中,那么期望的效果仍然有效.看到:
private void DisplayHtml(string html)
{
webBrowser1.Navigate("about:blank");
try
{
if (webBrowser1.Document != null)
{
webBrowser1.Document.Write(string.Empty);
}
}
catch (CastException e)
{ } // do nothing with this
webBrowser1.DocumentText = html;
}
Run Code Online (Sandbox Code Playgroud)
因此,每次DisplayHtml执行函数时,我都会CastException从if语句中收到一个,因此永远不会达到if语句的内容.但是,如果我注释掉该if语句以便不接收CastException,则浏览器控件不会更新.我怀疑Document属性背后的代码还有另一个副作用导致了这种效果,尽管它也引发了异常.
无论如何,我希望这有助于人们.
Thu*_*rGr 22
你可以做到,而不是导航到空白
webBrowser1.DocumentText="0";
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write(theHTML);
webBrowser1.Refresh();
Run Code Online (Sandbox Code Playgroud)
无需等待事件或其他任何事情.您可以检查MSDN for OpenNew,而我已经在我的一个项目中测试了初始DocumentText分配,并且它可以工作.
由于某些原因,m3z(使用该DisplayHtml(string)方法)提供的代码在我的情况下不起作用(第一次除外).我总是从字符串中显示html.这是我与WebBrowser控件的战斗后的版本:
webBrowser1.Navigate("about:blank");
while (webBrowser1.Document == null || webBrowser1.Document.Body == null)
Application.DoEvents();
webBrowser1.Document.OpenNew(true).Write(html);
Run Code Online (Sandbox Code Playgroud)
每次为我工作.我希望它对某人有帮助.