1

我有一个for循环到一个站点并发布到它的表单。对于listbox我希望它等待用户将数据填写到站点中的每个项目,然后移动。这里的关键点是“等待”。

所以我的问题是:是否可以for循环等待用户输入?

这是for我正在工作的循环,以便将数据加载到表单中:

if (webBrowser1.DocumentText.Contains("Welcome"))
{   
    for (int i = 0; i < listBox4.Items.Count; i++ )
    {

        listBox4.SetSelected(i, true);
        listBox5.SetSelected(i, true);
        //coded to submit to form

        Application.DoEvents();
    }
}

这是在网站上单击提交的代码:

Application.DoEvents();
foreach (HtmlElement webpageelement in allelements)
{

     if (webpageelement.GetAttribute("value") == "Submit")
     {
         webpageelement.InvokeMember("click");
         Application.DoEvents();

     }

 }

我也尝试过制作一个for没有代码的循环以使其继续。例如:i++ 并发表if声明以使其继续,但这落后于我的界面。

4

1 回答 1

1

for执行一个或一个while循环来等待用户输入并不是一个好的解决方案。不要那样做。您的程序将在等待条件使其退出循环的同时不断工作。相反,您应该使用事件或其他方式找到解决方案。

如果您不想使用Form.ShowDialog()问题评论中提出的解决方案,您可以提出类似的建议:

有一个全局变量来保存我们正在处理的 listBox 项的索引:

int currentItemIndex;

在您的按钮上添加一个Click事件。Submit当用户点击 时Submit,它会调用将处理下listBox一项的方法:

private void buttonSubmit_Click(Object sender, EventArgs e) {
    // Process next listBox item
    ProcessNextItem();
}

处理下listBox一项的方法:

private void ProcessNextItem() {
    currentItemIndex += 1;
    if (currentItemIndex >= listBox.Items.Count) {
        // We have gone through all listBox items

        // Do nothing
    } else {
        // Fill predefined information to the website
        website.SomeField = listBox.Items[currentItemIndex].SomeField; // Whatever you do to fill predefined information
}

Submit并在开始时调用一个方法(用户在处理第一项之前不点击listBox):

private void Start() {
    currentItemIndex = -1;
    ProcessNextItem();
}
于 2011-10-28T23:37:58.970 回答