Mark Ismail
Mark Ismail

Reputation: 720

Webview 2 .NET (Windows Forms) NullReferenceException

Microsoft has finally released a pre-release of Webview2 for .NET. I followed the steps, but I keep getting a NullReferenceException on loading the form. How can I fix this?

System.InvalidOperationException: 'An error occurred creating the form. See Exception.InnerException
for details.  The error is: Object reference not set to an instance of an object.'

NullReferenceException: Object reference not set to an instance of an object.

This exception was originally thrown at this call stack:
Microsoft.Web.WebView2.WinForms.WebView2.OnVisibleChanged(System.EventArgs)
  System.Windows.Forms.Control.AssignParent(System.Windows.Forms.Control)
  System.Windows.Forms.Control.ControlCollection.Add(System.Windows.Forms.Control)
  System.Windows.Forms.Form.ControlCollection.Add(System.Windows.Forms.Control)
  Repair_VIP.Form_test.InitializeComponent() in Form_test.Designer.vb

Upvotes: 2

Views: 7635

Answers (2)

Asgar
Asgar

Reputation: 61

I also got nullreferenceexception on CoreWebView2. When calling webView. CoreWebView2.NavigateToString(); I added this before calling the Navigate method.

 await webView.EnsureCoreWebView2Async(null);

and everything worked fine.

Upvotes: 6

pipalot
pipalot

Reputation: 100

I came here because I had the same problem. A null reference exception was thrown whilst the form was loading. In my case it was because CoreWebView2 is null while the form is loading.

For example, you can't do this while the form is loading:

webView.CoreWebView2.Navigate(url)

because CoreWebView2 is null.

You can handle the CoreWebView2Ready event to determine that CoreWebView2 has finished initialising and has stopped being null. For example:

private void WebView_CoreWebView2Ready(object sender, EventArgs e)
{
    // Now I know that CoreWebView2 is not null, I can do some work with it
    webView.CoreWebView2.Navigate(myUrl);
}

Of course it is unlikely that you would want to Navigate from inside that event, but I have used it just as an example.

So in summary, make sure your code doesn't mention CoreWebView2 during events firing while the form is loading, until you know that CoreWebView2 is ready.

Upvotes: 2

Related Questions