private void button5_Click(object sender, EventArgs e)
{
HtmlElementCollection links = webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement link in links)
{
if (link.GetAttribute("className")== "input-style1 psgn-name")
{
textBox10.Text = link.GetAttribute("id");
}
}
}
结果:我只获得4个元素的第4个元素id的id,具有相同的类。现在如何获得3元素id的其余部分?
答案 0 :(得分:0)
在文本框中,每次都会覆盖ID。您需要在文本框中连接字符串。所以......
private void button5_Click(object sender, EventArgs e)
{
HtmlElementCollection links = webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement link in links)
{
if (link.GetAttribute("className")== "input-style1 psgn-name")
{
textBox10.Text += link.GetAttribute("id") + ",";
}
}
// Remove last comma
if(!string.IsNullOrWhiteSpace(textBox10.Text)){
textBox10.Text = textBox10.Text.Substring(0, textBox10.Text.Length - 1);
}
}
现在,在文本框中,您可以看到以逗号分隔的元素ID列表。
如果要设置不同的文本框:
private void button5_Click(object sender, EventArgs e)
{
HtmlElementCollection links = webBrowser1.Document.GetElementsByTagName("input");
int i = 10;
foreach (HtmlElement link in links)
{
if (link.GetAttribute("className")== "input-style1 psgn-name")
{
foreach(Control ctrl in Controls)
{
if (ctrl is TextBox){
TextBox tb = (CheckBox)c;
if(tb.Name == "textBox" + i) {
i++;
tb.Text = link.GetAttribute("id");
}
}
}
}
}
}
或者
private void button5_Click(object sender, EventArgs e)
{
HtmlElementCollection links = webBrowser1.Document.GetElementsByTagName("input");
int i = 10;
foreach (HtmlElement link in links)
{
if (link.GetAttribute("className")== "input-style1 psgn-name")
{
TextBox tb = Controls.Find("textBox" + i) as TextBox;
i++;
if(tb != null) {
tb.Text = link.GetAttribute("id");
}
}
}
}
答案 1 :(得分:0)
每次循环迭代都会覆盖文本值。
更新的代码:
private void button5_Click(object sender, EventArgs e)
{
HtmlElementCollection links = webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement link in links)
{
if (link.GetAttribute("className")== "input-style1 psgn-name")
{
textBox10.Text += link.GetAttribute("id");
}
}
}
如果您想说如果将前四个项目存在于不同的文本框中,那么您需要填充一个列表,然后像这样引用它:
private void button5_Click(object sender, EventArgs e)
{
HtmlElementCollection links = webBrowser1.Document.GetElementsByTagName("input");
List<String> results = new List<String>();
foreach (HtmlElement link in links)
{
if (link.GetAttribute("className")== "input-style1 psgn-name")
{
results.Add(link.GetAttribute("id"));
}
}
textbox10.Text = results[0];
textbox11.Text = results[1]; etc....
}
使用Linq可以提供更优雅的解决方案:
//需要使用System.Linq
String[] results = (from itm in links where itm.GetAttribute("className") == "input-style1 psgn-name" select itm.GetAttribute("id")).ToArray();
然后用数组元素填充你的框。