开发者

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

开发者 https://www.devze.com 2023-01-09 19:08 出处:网络
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'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^ e开发者_C百科lement = 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.


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.


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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消