X

Displaying custom HTML in WebBrowser control

I am using WebBrowser control to show preview of automatically generated HTML. Users can select options and preview pane reflects those changes automatically. WebBrowser control has some problems that have been here for years already. Here is my example about how to show custom HTML in WebBrowser control.

Problem

When we look at methods and properties of WebBrowser control our common sense tells us that something like this should work (VB.NET users: delete “;” after this line):

webBrowser1.DocumentText = "some text here";

And it works – only once. All subsequent assignments change nothing. When we try to refresh WebBrowser control we get only white are. Setting AllowNavigation propertyto true – some guys suggest it – has no effect also.

Solution

To get all assignments works after first one we need to navigate to some page. # is good candidate because it “exists” also in local machine for sure. And that’s not enough – we need to write something to document. After that we can show our custom HTML.

private void DisplayHtml(string html)
{
    webBrowser1.Navigate("#");
    if (webBrowser1.Document != null)
    {
        webBrowser1.Document.Write(string.Empty);
    }
    webBrowser1.DocumentText = html;
}

NB! You should set AllowNavigation property to true before you deal with contents shown to users.

Keeping users on generated page

Now we can show HTML correctly and everything seems to be okay. But are we finished? Answer is yes if we want users to be able to follow the links we show to them and no if we want to keep users on generated page.

Currently we allowed navigation because otherwise we cannot move to #. We have to allow this navigation and disable all other navigation. Fortunately there isNavigating event of WebBrowser. In Navigating event we can do our filtering.

private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
    if (e.Url.ToString() != "#")
        e.Cancel = true;
}

So, that’s it. We can now display our custom HTML in WebBrowser control as many times as we want. If you have some better trick then please let me know!

Liked this post? Empower your friends by sharing it!
Categories: .NET C#

View Comments (109)

  • hmm .. what would happen if you enable navigation, navigate to blank, and then disable navigation again?

  • ThankYOU, that realy solved all my problems!

    Making a litle twitter c# app so custom html is needed, Thanks!

  • What if the design mode was enabled for the browser control? If you have design mode enabled the allowNavigate should be false for the design mode to work. I am building a web site builder which is based on browser control (in design mode) and mshtml.dll.
    Any tips would be highly appreciated. Thanks

  • Thanks, this solved the problem that using only DocumentText property inside a Vb application it works only the first time.

  • How can i make this work for vba? I"m using this in ms access. This below works but when i move to another record, it does not update the activex webbrowser. It goes blank.

    Forms![frm_EmailViewerTest].Form.WebBrowser2.Navigate "#"

    Forms![frm_EmailViewerTest].Form.WebBrowser2.Document.Write Forms![frm_EmailViewerTest].[TestEmails_subform].[Form]![EMLText]

  • Great article! I am trying to run mozilla in my webbrowser control, having some issues...

  • If you desire to get much from this piece of writing then you have
    to apply such methods to your won blog.

  • If you want to get much from this paragraph
    then you have to apply these strategies to your
    won blog.

  • Hello, just wanted to say, I enjoyed this article.

    It was helpful. Keep on posting!

  • YGR slot เป็นหนึ่งในผู้นำเสนอเกมสล็อตออนไลน์ที่ได้รับความนิยมอย่างมากในประเทศไทย ด้วยประสิทธิภาพของเกมและบริการที่ดีเยี่ยม YGR slot จึงเรียกร้องนักพนันออนไลน์จำนวนมากให้มาทดลองเล่นเกมสล็อตที่นานาชนิด

  • Discovering out 918KISS can enhance your own on the internet gaming journey into a journey packed together with
    enthusiasm plus opportunities. Since considered one of this the majority of common mobile phone gambling establishment apps throughout The southeast Asia, 918KISS features
    some sort of broad assortment associated with
    video games through video poker machines
    in order to desk game titles, most designed towards give the captivating encounter pertaining to gamers connected
    with virtually all levels. No matter whether you are the beginner seeking to explore 918KISS or even a great
    experienced person striving to boost the strategies, understanding the particular system's features and gameplay
    might appreciably effect the winning potential.

  • I like the valuable info you provide in your articles. I'll bookmark your blog and check again here frequently.
    I am quite certain I will learn lots of new stuff right here!
    Good luck for the next!

  • Hello very cool web site!! Man .. Excellent .. Amazing ..
    I will bookmark your blog and take the feeds also?
    I am satisfied to seek out a lot of useful info right
    here in the put up, we want work out more strategies in this regard, thanks for sharing.
    . . . . .

  • Everything is very open with a clear description of the
    challenges. It was really informative. Your website is very helpful.

    Thank you for sharing!

  • If you are going for finest contents like I do, only
    pay a visit this site all the time for the reason that it provides quality contents, thanks

  • Its like you read my mind! You seem to know so much about this, like you
    wrote the book in it or something. I think that you can do with a few pics to
    drive the message home a bit, but instead of that, this
    is fantastic blog. An excellent read. I'll definitely be back.

  • Pretty! This has been a really wonderful article. Thank you for providing this information.

  • Hey! I'm at work surfing around your blog from
    my new iphone! Just wanted to say I love reading your blog and
    look forward to all your posts! Keep up the fantastic work!

  • Thanks for every other great article. The place else could anybody get that kind of information in such an ideal manner of writing?
    I've a presentation subsequent week, and I'm at the search for such info.

  • Have you ever considered writing an ebook or guest authoring on other blogs?
    I have a blog based on the same subjects you discuss and would love to have
    you share some stories/information. I know my subscribers would value your
    work. If you're even remotely interested, feel free to shoot me an e mail.

  • id="firstHeading" class="firstHeading mw-first-heading">Search results

    Help

    English

    Tools

    Tools
    move to sidebar hide

    Actions

    General

  • I believe this is one of the most vital information for me.
    And i'm glad reading your article. But want to remark on some general things, The
    website taste is great, the articles is truly great : D.
    Just right task, cheers

  • I used to be recommended this blog through my cousin. I'm not sure whether this submit is written by means of him
    as nobody else realize such specific about my
    difficulty. You are amazing! Thank you!

  • id="firstHeading" class="firstHeading mw-first-heading">Search results

    Help

    English

    Tools

    Tools
    move to sidebar hide

    Actions

    General

  • Thanks , I have just been looking for information approximately this subject
    for ages and yours is the greatest I've discovered till now.
    However, what concerning the conclusion? Are you sure in regards to the source?

  • Excellent beat ! I would like to apprentice while you
    amend your site, how can i subscribe for
    a blog site? The account aided me a acceptable deal.
    I had been a little bit acquainted of this your broadcast offered
    bright clear concept

  • Gmail Accounts,NetfliTikTok,youtubeboosts, Author at
    YoutubeBoosts.NI,Facebook,Instagram - YoutubeBoosts.NIx ,
    Trading AccountsDveloper Accounts,Social Accounts,Paypal,
    Payoneer,Buy zelle Accounts,Other’s Accounts,Buy TikTok Ads Accounts,
    Bing Ads,Taboola Ads,Zeropark - visitvcc.com

  • Wow, this paragraph is pleasant, my younger sister is
    analyzing these things, so I am going to let know her.

  • I visited multiple web pages but the audio feature for audio songs existing at this site is truly marvelous.

  • Attractive component of content. I simply stumbled upon your web site and in accession capital to claim that I get in fact enjoyed
    account your blog posts. Any way I'll be subscribing to your feeds or even I achievement you get
    right of entry to consistently fast.

  • Hi just wanted to give you a quick heads up and let you know
    a few of the pictures aren't loading properly. I'm not sure why but I think
    its a linking issue. I've tried it in two different browsers and both show the same results.

  • I every time spent my half an hour to read this web site's content every day along with a mug
    of coffee.

  • you are in reality a just right webmaster.
    The site loading velocity is amazing. It sort of feels that you are doing any distinctive trick.
    Furthermore, The contents are masterwork. you have performed a excellent process in this matter!

  • I've read a few excellent stuff here. Certainly worth bookmarking for revisiting.
    I surprise how so much attempt you put to make one of these
    great informative site.

  • My spouse and I stumbled over here by a different page and thought I might check things out.
    I like what I see so i am just following you.
    Look forward to finding out about your web page for a second time.

  • Hi to every one, it's actually a good for me to pay a quick visit this web site, it contains important Information.

  • What's up, this weekend is pleasant in favor
    of me, since this point in time i am reading this impressive educational article here
    at my residence.

  • It's remarkable to pay a quick visit this website and reading the views of all friends
    about this post, while I am also eager of getting familiarity.

  • Hi to all, it's actually a fastidious for me to visit this web
    site, it includes valuable Information.

  • Hey there! Would you mind if I share your blog with
    my myspace group? There's a lot of folks that I think would really appreciate your content.
    Please let me know. Cheers

  • When someone writes an piece of writing he/she retains the
    idea of a user in his/her brain that how a user can understand it.
    Therefore that's why this post is outstdanding. Thanks!

  • My partner and I stumbled over here different web
    address and thought I might check things out. I like
    what I see so now i'm following you. Look forward to
    exploring your web page again.

  • Sᴡeet blog! I found it while broԝsing oon Yajoo News.
    Do you have any suggestions on how to get listed in Yahoo News?
    I've been trying for a while but I never ѕeewm to get there!
    Cheеrs

    My web-site gay

  • Hey there, You have done a fantastic job. I will certainly digg it and personally recommend to my
    friends. I'm confident they'll be benefited from this website.

  • Hello my loved one! I wish to say that this post is amazing, great written and include approximately all vital
    infos. I would like to peer more posts like this
    .

  • El proceso de obtencion es simple y rapido.
    Ya sea que uses Android o iOS, la app esta disenada para ofrecer una experiencia fluida, con acceso
    a cientos de eventos deportivos y juegos de
    casino en cuestion de segundos.

  • It's great that you are getting thoughts from this piece of
    writing as well as from our dialogue made at this place.

    Take a look at my web site - Visit Site

  • At this moment I am ready to do my breakfast, later than having my breakfast coming yet again to read other news.

  • Hi there to all, how is all, I think every one is getting more from this web site, and your views are nice in support of new viewers.

  • Hi, I think your website might be having browser compatibility issues.
    When I look at your website in Safari, it looks fine but when opening in Internet Explorer,
    it has some overlapping. I just wanted to give you a
    quick heads up! Other then that, fantastic blog!

  • Everything is very open with a very clear clarification of the issues.
    It was definitely informative. Your site is very helpful.
    Many thanks for sharing!

  • My family all the time say that I am killing my time here at net,
    but I know I am getting know-how all the time by reading thes nice articles
    or reviews.

  • I always spent my half an hour to read this
    web site's posts daily along with a mug of coffee.

  • I was suggested this website by my cousin. I'm not sure whether this post
    is written by him as no one else know such detailed about my
    trouble. You're incredible! Thanks!

  • Hmm it appears like your site ate my first comment
    (it was extremely long) so I guess I'll just sum it up what I had written and say, I'm thoroughly enjoying your blog.

    I as well am an aspiring blog blogger but I'm still new to
    the whole thing. Do you have any points for newbie blog writers?

    I'd genuinely appreciate it.

  • I was recommended this web site by my cousin. I'm not sure
    whether this post is written by him as nobody else know such detailed about my difficulty.
    You are amazing! Thanks!

  • We're a group of volunteers and opening a new scheme in our community.
    Your web site provided us with valuable information to work on. You've done an impressive job and our whole community will
    be thankful to you.

    Visit my blog gut drops weight loss

  • What's up it's me, I am also visiting this web
    site on a regular basis, this website is actually nice and the people are in fact sharing good thoughts.

  • I am really enjoying the theme/design of your website. Do you
    ever run into any browser compatibility problems? A few of my blog
    audience have complained about my blog not working correctly in Explorer
    but looks great in Firefox. Do you have any advice to help fix this problem?

  • Thanks for finally talking about > Displaying custom HTML in WebBrowser control
    < Liked it!

  • Do you mind if I quote a few of your articles as long as I provide credit and sources back to your weblog?
    My blog site is in the very same niche as yours and my users would definitely benefit from some of the information you provide here.
    Please let me know if this ok with you. Many thanks!

  • I think that is one of the most vital information for me.
    And i am glad reading your article. However should remark on few basic
    things, The site style is wonderful, the articles is in reality nice : D.
    Good activity, cheers

  • Write more, thats all I have to say. Literally, it seems as though you relied on the video to make
    your point. You clearly know what youre talking about, why throw away your intelligence on just posting videos to your site when you could be giving us something informative to read?

  • Hello to all, how is the whole thing, I think every one is getting more
    from this web page, and your views are fastidious in support of
    new people.

  • Por fim, para aqueles que procuram um jogo simples, mas ao mesmo tempo divertido e com uma temática única, poucas opções são tão cativantes e gratificantes quanto o jogo Big Bass Bonanza. A F12 bet é operada pela F12 do Brasil Jogos Eletrônicos Ltda. e possui licença para atuar no país expedida pelo Governo Federal. A sua autorização foi emtida pela Secretaria de Prêmios e Apostas do Ministério da Fazenda, sob nº 2.104-5, respeitando as regras de regulamentação do mercado de apostas no Brasil. Ao jogar os slots da F12.bet, você pode participar da oferta “domingo dos slots”. Basicamente, são R$ 80.000 divididos entre 93 premiações, sendo possível receber até R$ 1000. Em comparação com o Amuleto Bet Cassino a F12 Bet parece mais focada na segurança do usuário. A casa de apostas online utiliza criptografia SSL avançada, verificação de identidade rigorosa e auditoria de jogos. Apesar de ter um valor mínimo de aposta ligeiramente mais elevado do que outros sites, jogar na F12 Bet é uma experiência que se destaca pela segurança e tranquilidade. 
    https://giftedmusicschool.softeero.com/lucky-jet-uma-analise-profunda-de-um-jogo-de-cassino-online-popular-na-1win-para-brasileiros/
    You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page. A volatilidade do jogo, por sua vez, é classificada como alta. Dessa maneira, a slot é indicada para usuários que estão em busca de premiações altas e que não se preocupam tanto com eventuais oscilações de saldo acima da média. No jogo Big Bass Splash, os jogadores embarcam em uma jornada emocionante em busca de prêmios substanciais. Com uma configuração padrão de 5 rolos, 3 linhas e 10 linhas de pagamento fixas, o jogo oferece uma experiência de jogo envolvente para jogadores de todos os níveis de habilidade. O objetivo é simples: formar combinações vencedoras de símbolos nos rolos para garantir prêmios incríveis.

  • Selir 77 Rattling nice design and wonderful content, hardly anything else we require :D.

  • Hi there! I know this is kinda off topic but I'd figured I'd ask.
    Would you be interested in exchanging links or maybe guest writing a blog article or vice-versa?
    My site goes over a lot of the same topics as yours and I feel we could greatly benefit from each other.
    If you're interested feel free to shoot me an e-mail.
    I look forward to hearing from you! Fantastic blog by the way!

  • Hi there, I do believe your blog could possibly be
    having web browser compatibility problems. Whenever I take a look at your blog
    in Safari, it looks fine however, when opening
    in Internet Explorer, it's got some overlapping issues.
    I simply wanted to give you a quick heads up!

    Other than that, great website!

    My page - lean drops

  • Hello I am so glad I found your blog, I really found you by error,
    while I was searching on Google for something else,
    Nonetheless I am here now and would just like to say thank
    you for a incredible post and a all round entertaining blog (I also love the theme/design), I don’t have time to
    look over it all at the moment but I have book-marked it and also included your RSS feeds, so when I have time I will be back to read much more, Please do keep up the superb work.

  • I was pretty pleased to discover this site. I need to to thank you for your time for this particularly fantastic read!!
    I definitely loved every little bit of it
    and i also have you saved to fav to see new stuff in your website.

  • Greetings! I've been reading your weblog for a long time now and finally got
    the courage to go ahead and give you a shout out from Lubbock Tx!
    Just wanted to tell you keep up the excellent work!

  • Ahaa, its nice dialogue regarding this article at this place
    at this weblog, I have read all that, so now me also commenting here.

  • Excellent, what a blog it is! This webpage provides valuable facts to us,
    keep it up.

  • This site was... how do I say it? Relevant!!
    Finally I have found something that helped me. Appreciate it!

  • I do not even know the way I stopped up right here, however I assumed this submit used to
    be great. I do not realize who you might be but
    definitely you are going to a well-known blogger if you happen to aren't already.
    Cheers!

  • Simply desire to say your article is as amazing.
    The clarity in your post is simply cool and i can assume you
    are an expert on this subject. Well with your permission allow me to grab your RSS feed to keep
    up to date with forthcoming post. Thanks a million and please carry on the gratifying work.

  • I don't even understand how I ended up right here, however I believed this submit was great.
    I don't know who you might be but definitely you are going to a famous blogger should you are not
    already. Cheers!

  • Today, I went to the beachfront with my children. I found a sea
    shell and gave it to my 4 year old daughter and said "You can hear the ocean if you put this to your ear." She
    placed the shell to her ear and screamed. There was a hermit crab inside and it pinched
    her ear. She never wants to go back! LoL I know this is totally off
    topic but I had to tell someone!

  • Hi there, i read your blog occasionally and i own a similar one
    and i was just curious if you get a lot of spam responses?
    If so how do you stop it, any plugin or anything you can advise?

    I get so much lately it's driving me crazy so any support is very much appreciated.

  • Hello, i think that i saw you visited my weblog thus i got here
    to go back the desire?.I'm attempting to find things to improve my site!I
    assume its ok to use some of your ideas!!

Related Post