Ben
Ben

Reputation: 2523

Parameter 'param_name' not found in collection

This is my first attempt at using ADO.NET for MySQL, and I have no idea what's going on. I keep getting the error Parameter '_name' not found in collection on the first parameter I try to define.

I have tried reordering, but no matter which way I put it, MySQL always catches up of the first line.

mySqlCommand = mySqlConnect.CreateCommand();
mySqlCommand.CommandText = "SELECT MajorEquipment.EquipmentNumber, MajorEquipment.EquipmentType, PlantAreaCodes.AreaCode " +
  "FROM MajorEquipment e INNER JOIN PlantAreaCodes a " +
  "ON e.PACId = a.PACId WHERE " +
  "(@EquipmentType IS NULL OR e.EquipmentType = @EquipmentType) " +
  "AND (@EquipmentNumber IS NULL OR e.EquipmentNumber = @EquipmentNumber) " +
  "AND (@AreaCode IS NULL OR a.AreaCode = @AreaCode)";

// The First line shows the error. I have tried @EquipmentType, 
// @EquipmentNumber, and @AreaCode in the first line.

mySqlCommand.Parameters["@EquipmentType"].Value = (string.IsNullOrEmpty(MeModel.EquipmentType) ? (object)DBNull.Value : MeModel.EquipmentType);
mySqlCommand.Parameters["@EquipmentNumber"].Value = (string.IsNullOrEmpty(MeModel.EquipmentNumber) ? (object)DBNull.Value : MeModel.EquipmentNumber);
mySqlCommand.Parameters["@AreaCode"].Value = (string.IsNullOrEmpty(MeModel.Location) ? (object)DBNull.Value : MeModel.Location);

mySqlReader = mySqlCommand.ExecuteReader();

The first parameter shows the error, but I'm starting to believe that it may be something to do with the Command string.

I have also tried replacing e and a with MajorEquipment and AreaCode respectively.

Why is this happening?

Here are my Tables for reference:

+----------------+    +-----------------+
| PlantAreaCodes |    | MajorEquipment  |
|----------------|    |-----------------|
| PACId (PKEY)   |    | MEId (PKEY)     |
| AreaCode       |    | EquipmentType   |
| AreaName       |    | PACId (FKEY)    |
| Comments       |    | EquipmentNumber |
+----------------+    +-----------------+

Upvotes: 2

Views: 1743

Answers (1)

Steve
Steve

Reputation: 216293

You need to add the parameters to the collection before settings their values or use the shortcut AddWithValue

mySqlCommand.Parameters.AddWithValue("@EquipmentType", (string.IsNullOrEmpty(MeModel.EquipmentType) ? (object)DBNull.Value : MeModel.EquipmentType));
mySqlCommand.Parameters.AddWithValue("@EquipmentNumber", (string.IsNullOrEmpty(MeModel.EquipmentNumber) ? (object)DBNull.Value : MeModel.EquipmentNumber));
mySqlCommand.Parameters.AddWithValue("@AreaCode", (string.IsNullOrEmpty(MeModel.Location) ? (object)DBNull.Value : MeModel.Location));

Upvotes: 2

Related Questions