Skip to content

NullReferenceException if using FindControl on a form having control w/o name attribute set #3

@fehdem

Description

@fehdem

I used this little piece of code to get access to an TextInputControl on a form.

using (var browser = new MechanizeBrowser())
{
  var page = await browser.NavigateAsync("https://<blabla>");
  if (page.IsHtml)
  {
    var form = page.Forms["login"];
    var queryfield = form.FindControl<TextInputControl>("param3");
    ....
  }
}

The login form contains some controls, some w/o having the name attribute set. This results in a NullReferenceException when calling form.FindControl.
I cloned the repro locally and found the issue in HtmlForm.cs.

public T FindControl<T>(string Name) where T : HtmlFormControl
{
  return (T)this.FirstOrDefault(item => item.Name != null && item.Name.Equals(Name,StringComparison.OrdinalIgnoreCase));
}

The code on Master lacks a check whether item.Name is set to any string. I added a null check as a bugfix. If I don't miss any side effect you may include this into your master as well.

Best regards,
Marcus

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions