mastofact
mastofact

Reputation: 550

How do I obtain a value of an HTML field with C#/C++

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.

Upvotes: 1

Views: 2331

Answers (4)

mastofact
mastofact

Reputation: 550

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.

Upvotes: 1

Ryan Hayes
Ryan Hayes

Reputation: 5310

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 -->

Upvotes: 0

Fabiano
Fabiano

Reputation: 5199

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

Upvotes: 0

Will Dean
Will Dean

Reputation: 39500

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.

Upvotes: 2

Related Questions