how to make a navigation statement if the textBox1.Text does not equal a url for WebView2 to search for text in duckduckgo / make a search instead of direct url navigation C# Winforms

core hacked 121 Reputation points
2021-03-27T11:23:46+00:00

Hello,
I have recently switched to the newer Edge Based WebView2 by Microsoft and I have experienced issues trying to search for just text/make a search query.
Before what I did with the IE Based WebBrowser, is that i would get the search string of duckduckgo and then replace the search text with textBox1's text.

I have copied the code from Microsoft start guide on webview and inserted an else statement, it only crashes the app does not search though. (Excluding URLs which it does with no problem.)

WebView2 rewritten code:

if (webView21 != null && webView21.CoreWebView2 != null)
            {
                webView21.CoreWebView2.Navigate(textBox1.Text);
            }
            else
            {
                webView21.CoreWebView2.Navigate("https://duckduckgo.com/?q=" + textBox1.Text + "&t=h_&ia=web");
            }
Developer technologies Windows Forms
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. core hacked 121 Reputation points
    2021-03-27T13:34:49.543+00:00

    I have solved it by making it a try, catch statement. Please feel free to leave a better suggestion if you have one.

     try
                 {
                     if (webView21 != null && webView21.CoreWebView2 != null)
                     {
                         webView21.CoreWebView2.Navigate(textBox1.Text);
                     }
                 }
                 catch
                 {
                     webView21.CoreWebView2.Navigate("https://duckduckgo.com/?q=" + textBox1.Text + "&t=h_&ia=web");
                 }
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.