tags:

views:

87

answers:

4

I'm using HtmlElement to get an HTML element by it's ID and trying to display this value and return it (as a String). The problem is that it sees it as an Object.

I have a webBrowser in the code with an HTML file that has:

<label id="Address" text="asdf"></label>

In my C++ header file I have

   HtmlElement^ element = this->webBrowser1->Document->GetElementById("Address");
String^ asdf = element->GetAttribute("text");
return asdf;

This builds, but when I launch the program, I get an exception "Object reference not set to an instance of an object."

I can't use System::Convert.ToString(); either, it won't let me build with that.

Any suggestions are appreciated. Thanks.

+2  A: 

Which line throws the exception - the first one or the second one?

There are 4 or 5 places in that code which could throw that exception, and I would start by working out which one it is.

Will Dean
Sorry, this line throws the exception.String^ asdf = element->GetAttribute("text");
John H.
@John H: Then your label isn't found and element is null.
Jesper Palm
@Jesper Palm: thanks, I had to add to check if it was null. I guess it is, and it's not finding my label/element now... :(
John H.
John - Jesper's advice in a comment on your question is really good, and you should try that.
Will Dean
A: 

Just use the "runat" attribute within your tag (note that I've changed the text's position):

<label id="Address" runat="server">asdf</label>

Then, in .cs code, you get the text using the text property of the object.

Response.Write(Address.Text);

The -> operator is not used for what you are trying to do. It is used combined with pointers. Check this documentation: -> Operator

Fabiano
I think that he is using c++ and the WebBrowser control. Not ASP.NET
Jesper Palm
Hmm you're right, I've read "C#" on the title. I might be blind, now I see the C++ =/
Fabiano
You saw correct. I edited from C# to C++.
John H.
A: 

This is under the assumption of using C#

You should be able to grab ahold of the label in the code behind by adding the runat="server" attribute to the label (even if it's just a plain old HTML label).

On the back end, you will then be able to access it by:

this.Address.InnerText

InnerText is the proper way to get the text from an HTML label in C#, not a text attribute. So instead of having this:

<label id="Address" text="asdf"></label> <!-- broke -->

use this with the codebehind I mentioned:

<label id="Address" runat="server">asdf</label> <!-- works great -->
Ryan Hayes
A: 

OK I finally figured out the problem after switching projects and coming back to it after a while.

I forgot the 'System::Object^ sender' part in my header file. Now all the HtmlElement stuff works.:

public: System::String^ GetAddress(System::Object^ sender)

Thanks for all your help.

John H.