T
T
TechNOIR2018-05-28 09:16:54
C++ / C#
TechNOIR, 2018-05-28 09:16:54

C#. How to fix NullReferenceException error?

Good afternoon.
There is a code that seems to build normally, but as soon as the launch starts, it crashes with an error -

Исключение типа "System.NullReferenceException" возникло в av.exe, но не было обработано в коде пользователя

The error refers to:
webBrowser1.Document.Click += docCompleted;
The event is assigned null where it is declared, is it possible to beat this somehow or can declare the event differently?
thanks in advance
The code
namespace av
{
  public partial class MainForm : Form
  {
    private Excel.Application ex = new Microsoft.Office.Interop.Excel.Application();
    public static string result;
    public static string first;
    public static string second;
    public static string urlo;
    public MainForm()
    {
      InitializeComponent();
      ex.Visible = false;
      ex.Workbooks.Open(sourcetext.Text,
                        Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                        Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                        Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                        Type.Missing, Type.Missing);
      LoadAndClick();	
    }
        private async void LoadAndClick()
    {
      int nach = Convert.ToInt32(strNtext.Text);
      int konech = Convert.ToInt32(strAlltext.Text);
        for (int i = nach; i <= konech; i++)
        {
        	first = st1text.Text + i.ToString();
        	second = st2text.Text + i.ToString();
        	Excel.Worksheet newsheet = (Excel.Worksheet)ex.Worksheets.get_Item(1);
      Excel.Range rngfirst = newsheet.Range[first];
      Excel.Range rngsec = newsheet.Range[second];
            urlo = "https://yandex.ru/images/search?family=yes&text="+rngfirst.Value+"+"+rngsec.Value;
            Debug.WriteLine(urlo);
            var tcs = new TaskCompletionSource<int>();
            HtmlElementEventHandler docCompleted = null;
      result = strestext.Text + i.ToString();
                    docCompleted = (s, e) =>
                    {
                        try
                        {
                            webBrowser1.Document.Click -= docCompleted;
                            string element = webBrowser1.Document.GetElementFromPoint(e.ClientMousePosition).GetAttribute("href");
                            Debug.WriteLine(element);
                            Regex regex = new Regex(@"img_url=(.*?)&pos=(.*?)&", RegexOptions.IgnoreCase);
                            foreach (Match match in regex.Matches(element))
                            {
                                Debug.WriteLine("Match 1: " + match.Groups[1].Value);
                                string sss = System.Uri.UnescapeDataString(match.Groups[1].Value);
                                Debug.WriteLine(s);
                                Excel.Worksheet sheet = (Excel.Worksheet)ex.Worksheets.get_Item(1);
                                Excel.Range rng3 = sheet.Range[result];
                                rng3.Value = sss;
                                int to = Convert.ToInt32(timeouttext.Text);
                                System.Threading.Thread.Sleep(to);
                                ex.Save();
                            }
                        }
                        finally
                        {
                    // отмечаем, что событие отработало. 
                    tcs.TrySetResult(0);
                        }
                    };
            webBrowser1.Navigate(urlo);
            Debug.WriteLine("Загрежно");
            webBrowser1.Document.Click += docCompleted;
            await tcs.Task; // ждем, когда событие сработает. 
       }
        ex.Workbooks.Close();
    }
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GavriKos, 2018-05-28
@GavriKos

The event can be assigned null - it does not throw exceptions from this. But it's worth checking webBrowser1 and Document for null. Debugger and try-catch in the teeth and go.

A
Alexander Yudakov, 2018-05-28
@AlexanderYudakov

There is no document yet, and we are already trying to subscribe to its events.
You have to wait until the document is loaded.
I suggest before that:
insert this:

for (var i = 0; ; ++i)
{
  await Task.Delay(500);
  if (webBrowser1.Document != null)
    break;
  else if (i == 20)
    throw new TimeoutException();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question