System.Windows.Forms.HtmlDocument.Body.get returned null

Asked

Viewed 68 times

-1

I am creating HTML elements by C# using Webbrowser, I am not using the URL property, just using pure code. When I try to use this command:

this.webBrowser1.DocumentText = "<head></head><body></body>";
var document = this.webBrowser1.Document;
document.Body.Style = "background-color:red;";

Makes that mistake:

System.Nullreferenceexception: 'Object reference not set to an instance of an object.'

System.Windows.Forms.HtmlDocument.Body.get returned null.

I already put this code above, within the Documentcompleted method of Webbrowser, but only that it is not called. Just for that I put in the constructor.

How do I make the above code work?

1 answer

1


It is not possible to manipulate the Documentuntil it has completed its initialization. You can use the filling DocumentCompleted.

private void Form1_Load(object sender, EventArgs e)
{            
    webBrowser1.DocumentText = "<html><head></head><body></body></html>";
    webBrowser1.DocumentCompleted += WebBrowser1_DocumentCompleted;
}

private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{            
    webBrowser1.Document.Body.Style = "background-color:red;";            
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.