Ayoub_B
Ayoub_B

Reputation: 700

C# NullReferenceException on Uri.AbsoluteUri

I have this piece of code:

WebBrowser wb = new WebBrowser();
wb.Url = new Uri("https://www.google.com/");
ProgressChanged += newWebBrowserProgressChangedEventHandler(webBrowser_ProgressChanged);

comboUrl.Text = wb.Url.AbsoluteUri;

But I am getting a NullReferenceException on the last line.

Am I missing something?

Upvotes: 0

Views: 1205

Answers (1)

kmcnamee
kmcnamee

Reputation: 5255

Calling .Url like your are is the same as calling Navigate

WebBrowser.Url Property

Setting this property is equivalent to calling the Navigate method and passing it the specified URL.

Problem is you are getting the null reference exception because the WebBrowser.Url is null until the WebBrowser control finishes navigating to the Url. You can call .Url in the event handler for Navigated the wb.Url property will return the current Url. For example you can do

private void Form1_Load(object sender, EventArgs e)
{
        WebBrowser wb = new WebBrowser();

        wb.Url = new Uri("https://www.google.com/");

        wb.Navigated += wb_Navigated;

       //wb.Url will be null here.  
}

void wb_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
        // url not null here..
        Debug.WriteLine((sender as WebBrowser).Url);
}

Upvotes: 1

Related Questions