webView2 uninitalize exception on navigate

G. Gunn - fs 146 Reputation points
2022-05-14T16:58:42.573+00:00

drag and drop WebView2 into a panel in winform as webView
here is my code

if (webView.CoreWebView2 == null) webviewInit();
webView.CoreWebView2.NavigateToString("https://finance.yahoo.com/quote/" + symbolTbx.Text); // this gets uninitialized exception during runtime.
...
async void webViewInit()

{
webView.Source = new Uri("https://finance.yahoo.com/quote/");
string userDataFolder = null;
CoreWebView2EnvironmentOptions options = null;
CoreWebView2Environment env = CoreWebView2Environment.CreateAsync("", userDataFolder, options).GetAwaiter().GetResult();
await webView.EnsureCoreWebView2Async(env);
}

what should I do?

Microsoft Edge
Microsoft Edge
A Microsoft cross-platform web browser that provides privacy, learning, and accessibility tools.
2,151 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Castorix31 81,831 Reputation points
    2022-05-14T18:37:56.953+00:00

    You must initialize it, either with Source as the doc says at Get started with WebView2 in WinForms apps
    or
    with EnsureCoreWebView2Async, like :

            private async void Form1_LoadAsync(object sender, EventArgs e)  
            {  
                webView21.CoreWebView2InitializationCompleted += new System.EventHandler<Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs>(webView21_CoreWebView2InitializationCompleted);  
                await InitializeAsync();             
            }  
    

    with

            private async Task InitializeAsync()  
            {  
                await webView21.EnsureCoreWebView2Async(null);  
            }  
    

    test URL :

            private void webView21_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)  
            {  
                if (webView21 != null && webView21.CoreWebView2 != null)  
                {                 
                    webView21.CoreWebView2.Navigate("https://www.microsoft.com");  
                }             
            }