Search code examples
c#visual-web-developer-2010

C# Foreach value in a using clause?


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();
    }
}

Solution

  • 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:

    • Extracted constant SQL into a class-level constant. Not necessary, but might clarify things.
    • Renamed all variables to be camelCase without underscores
    • Wrapped lines for StackOverflow - you probably don't need as much wrapping in your code
    • Removed redundant explicit call to Dispose (as the using statement already calls Dispose)