C# 代码一直运行到抛出异常的地步,我如何打破它?
因此,我有这个应用程序,它将帮助我为我的一些客户发送电子邮件,在最后一次调用之前,一切都正常工作。 它按下按钮并让我登录,但随后它继续运行代码并再次循环回按钮单击,这会给我带来一个错误,因为按钮不再存在,因为我们已经登录,所以HtmlDocument不再相同。 我试着回报;最后,但这并没有阻止我的代码运行,我在这一点上完全迷失了方向。 我试着用断点调试它,结果似乎是这样的,正如我再次提到的代码循环 异常消息:System.NullReferenceException:“对象引用” 未设置为对象的实例。'C# 代码一直运行到抛出异常的地步,我如何打破它?,c#,html,exception,attributes,htmlelements,C#,Html,Exception,Attributes,Htmlelements,因此,我有这个应用程序,它将帮助我为我的一些客户发送电子邮件,在最后一次调用之前,一切都正常工作。 它按下按钮并让我登录,但随后它继续运行代码并再次循环回按钮单击,这会给我带来一个错误,因为按钮不再存在,因为我们已经登录,所以HtmlDocument不再相同。 我试着回报;最后,但这并没有阻止我的代码运行,我在这一点上完全迷失了方向。 我试着用断点调试它,结果似乎是这样的,正如我再次提到的代码循环 异常消息:System.NullReferenceException:“对象引用” 未设置为对象的
假设
webBrowser1.DocumentCompleted
是一个事件,则每次单击该按钮时,都会向该事件添加另一个代理。你应该把这一行移到你的构造函数中。你可能的重复应该只在代码中注册一次事件文档Completed,而不是每次调用button1 click事件。但是我只单击按钮一次。
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");
}
}
}