0

this is the error

And this is the dropdown menu I used

 <select id="IDmoto" name="IDmoto" class="combobox">
     <option>@siteResource1.motorisation</option>
 </select>

1 Answers1

0

In the image you provided, you either tried to get a Form named "IDmoto" that doesn't exist in the collection or tried to get a control named "IDmoto". The FormCollection is a collection of forms, but you can get the collection of controls using FormCollection["FormName"].Controls, or simply FormName.Controls. Using your code:

public ActionResult Resultat(FormCollection forms)
{
    // Just realized that you specified the control as a combobox
    // The SelectedIndex is already an int.
    int IDMotorisation = forms["FormName"].Controls["IDmoto"].SelectedIndex;
    List<Piece> pieces = new List<Piece>();
    foreach (Piece item in db.Pieces)
    {
        if (IDMotorisation == item.IDMotorisation)
        {
            pieces.Add(item);
        }
    }
}

or, only calling one form:

public ActionResult Resultat(Form form)
{
    int IDMotorisation = form.Controls["IDmoto"].SelectedIndex;
    List<Piece> pieces = new List<Piece>();
    foreach (Piece item in db.Pieces)
    {
        if (IDMotorisation == item.IDMotorisation)
        {
            pieces.Add(item);
        }
    }
}

The meaning of the NullReferenceException is caused by referencing an object that is null. With the FormCollection, if the FormCollection can't find the form specified, it will return null. More NullReferenceException information here.

Welcome to stackoverflow, by the way!

JJtheJJpro
  • 81
  • 3
  • 7
  • Thanks for your welcome. – Fadi Hamza May 25 '20 at 18:15
  • Please which namespace I should use with "Form form" in the parameter in the second method because it shows an error which it says: "The type or namespace name 'Form' could not be found (are you missing a using directive or an assembly reference?)" – Fadi Hamza May 25 '20 at 18:20
  • That's odd. If the FormCollection parameter isn't giving you an error, the Form parameter shouldn't be giving you an error...make sure that you have the using directive `using System.Windows.Forms;`. Send me a picture of your code (with the Form parameter) – JJtheJJpro May 26 '20 at 17:45
  • Also, I just realized this, the `form.Controls["IDmoto"].SelectedIndex` should be changed to `((ComboBox)form.Controls["asdf"]).SelectedIndex` – JJtheJJpro May 26 '20 at 17:46