How to get HTML textbox value?

两盒软妹~` 提交于 2019-12-01 07:10:32

问题


I am trying to get values of few textboxes on a website in a C# WinForms app. It is input type text, set to readonly, but when I try to read it in my app using

string price = webBrowser1.Document.GetElementById("price").GetAttribute("value");

it returns an empty string. When I try to set some other (not readonly) input value using .SetAttribute("value", "testValue"), it works just fine.

Anyone could help me with this please?


回答1:


Unfortunately the value from the text box cannot be retrieved using GetAttribute.

You can use the following code to retrieve the value:

dynamic elePrice = webBrowser.Document.GetElementById("price").DomElement;
string sValue = elePrice.value;

If you are not able to use dynamic (i.e. .NET 4+) then you must reference the 'Microsoft HTML Object Library' from the COM tab in Visual Studio and use the following:

mshtml.IHTMLInputElement elePrice = (mshtml.IHTMLInputElement)webBrowser.Document.GetElementById("price").DomElement;
string sValue = elePrice.value;

EDIT: This has been tested with the following code:

webBrowser.Url = new Uri("http://files.jga.so/stackoverflow/input.html");

webBrowser.DocumentCompleted += (sender, eventArgs) =>
{
     var eleNormal = (IHTMLInputElement)webBrowser.Document.GetElementById("normal").DomElement;
     var eleReadOnly = (IHTMLInputElement)webBrowser.Document.GetElementById("readonly").DomElement;
     var eleDisabled = (IHTMLInputElement)webBrowser.Document.GetElementById("disabled").DomElement;

     MessageBox.Show(eleNormal.value);
     MessageBox.Show(eleReadOnly.value);
     MessageBox.Show(eleDisabled.value);
};



回答2:


try to use innertext

string price = webBrowser1.Document.GetElementById("price").InnerText;


来源:https://stackoverflow.com/questions/24091944/how-to-get-html-textbox-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!