I'm trying to loop through an array of strings using the foreach control, and then use each value to insert information in the database. Could someone help me understand why within the using clause I can't use the foreach variable?
string[] ship_ids = ShipsInScope.Split('|');
foreach (string ship_id in ship_ids)
{
using (SqlCommand InsertCommand = new SqlCommand("insert into PROJECT_SHIP (CR_Number, Ship_Id) VALUES (@CR_Number, @CCF_Number)", DBConn))
{
InsertCommand.Parameters.Add("@CR_Number", SqlDbType.NVarChar, 10).Value = CRNumber;
InsertCommand.Parameters.Add("@Ship_Id", SqlDbType.NVarChar, 10).Value = Ship_Id;
InsertCommand.ExecuteNonQuery();
InsertCommand.Dispose();
}
}
C# is case-sensitive. Your iteration variable is
ship_idbut you're trying to useShip_Idin the loop.Ideally, use C# naming conventions instead (and for other variables too):
Notes:
camelCasewithout underscoresDispose(as theusingstatement already calls Dispose)