代码一直运行到它抛出异常的程度我该如何打破它?

时间:2017-04-03 12:16:11

标签: c# html exception attributes htmlelements

所以我有这个应用程序,它将帮助我为我的一些客户发送电子邮件,一切正常,直到它到达最后一次调用。 它按下按钮并登录,但随后它继续运行代码并再次循环返回按钮点击,因为按钮不再存在因为我们已经登录所以HtmlDocument不再相同。 我试图回报;在最后,但这并没有阻止我的代码运行,并在此时我相当丢失。 我已尝试使用断点进行调试,而且似乎是,正如我所提到的那样,再次遍历代码。

  

异常消息:System.NullReferenceException:'对象引用   没有设置为对象的实例。'

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NoTheme
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            webBrowser1.Navigate("https://accounts.google.com/ServiceLogin#identifier");

        }

        private void button1_Click(object sender, EventArgs e)
        {
            HtmlDocument startDoc = webBrowser1.Document;
            HtmlElement usernameElement = startDoc.GetElementById("Email");
            HtmlElement loginBtnElement = startDoc.GetElementById("signIn");

            usernameElement.SetAttribute("value", "theGmail@gmail.com");
            loginBtnElement.InvokeMember("click");
            webBrowser1.DocumentCompleted += WebBrowser1_DocumentCompleted;
        }

        private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

            HtmlDocument startDoc = webBrowser1.Document;
            HtmlElement usernameElement = startDoc.GetElementById("Passwd");
            HtmlElement loginBtnElement = startDoc.GetElementById("signIn");

            usernameElement.SetAttribute("value", "thePassword"); //this is where it throws the error
            loginBtnElement.InvokeMember("click");
        }
    }
}

0 个答案:

没有答案