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_id
but you're trying to use Ship_Id
in the loop.
Ideally, use C# naming conventions instead (and for other variables too):
// Declared outside the method.
private const string InsertSql =
"insert into PROJECT_SHIP (CR_Number, Ship_Id) " +
"VALUES (@CR_Number, @CCF_Number)";
...
string[] shipIds = ShipsInScope.Split('|');
foreach (string shipId in shipIds)
{
using (SqlCommand command = new SqlCommand(InsertSql, connection))
{
command.Parameters.Add("@CR_Number", SqlDbType.NVarChar, 10)
.Value = crNumber; // Unclear what this means
command.Parameters.Add("@Ship_Id", SqlDbType.NVarChar, 10)
.Value = shipId;
command.ExecuteNonQuery();
}
}
Notes:
camelCase
without underscoresDispose
(as the using
statement already calls Dispose)