Using String.Format when passing DateTime arguments type to DB. Exception is thrown. What is wrong?

379 views Asked by At
         object args = new object[] { "Project", "ProjectName", "@PrName", "ProjectStartDate", "@StartDate", "ProjectEndDate", "@EndDate", "ProjectId", "@Id" };

//******************this line causes exception thrown *******************

            string commandString = string.Format(@"UPDATE FROM {0} SET {1} = {2}, {3} = {4} , {5} = {6} WHERE {7} = {8}", args);

            command.CommandText = commandString;
            command.CommandType = CommandType.Text;
            command.Connection = connection;
            command.Parameters.Add("@Id", SqlDbType.Int).Value = selId;
            command.Parameters.Add("@PrName", SqlDbType.Text).Value = projectName;

            command.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = startDate;
            command.Parameters.Add("@EndDate", SqlDbType.DateTime).Value = endDate;

            connection.Open();
            int result = command.ExecuteNonQuery();

// **************** exception details *****************************

System.FormatException was unhandled Message=Index (zero based) must be greater than or equal to zero and less than the size of the argument list. Source=mscorlib StackTrace: at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args)

   at System.String.Format(IFormatProvider provider, String format, Object[] args)

   at System.String.Format(String format, Object arg0)

   at DAL.DataAccess.UpdateRec(Int32 selId, String projectName, DateTime startDate, DateTime endDate) in \Projects\Consulting\DAL\DataAccess.cs:line 106
   at Consulting.frmProject.btnAdd_Click(Object sender, EventArgs e) in \frmProject.cs:line 48
1

There are 1 answers

1
Pushkar P On BEST ANSWER

try below code. It should work.

object[] args = new object[]   { "Project", "ProjectName", "@PrName", "ProjectStartDate", "@StartDate", "ProjectEndDate", "@EndDate", "ProjectId", "@Id" };

If it works please mark as answer.