问题
No longer relevant:
In one of the comments below the OP mentions a private object DateTime() { throw new NotImplementedException(); }
slipping in. It happens .
I have a DateTime
field in a SqlCe database. I wish to add the time the row is created hence the need for:
DateTime now = DateTime.Now;
However this issue i am getting is that this is 'a method which is not valid in the given context'. Im guessing its something to do with it being static and im using it in a non static function perhaps ?
Just to ask in the same thread
SqlParameter Created = new SqlParameter("@Created", SqlDbType.DateTime);
**Created.Value = DateTime.Now; <--- gives error DateTime() is method which is not valid in the given context**
SqlCeCommand mySQLCommand = dbCon.CreateCommand();
mySQLCommand.CommandText = "INSERT into table (Created) VALUES (@Created)";
mySQLCommand.Parameters.Add(vetCreated);
mySQLCommand.ExecuteNonQuery();
Does this seem like a resonable list commands to add DateTime
to the database?
回答1:
In this line:
mySQLCommand.Parameters.Add(vetCreated);
I don't know what vetCreated
is, but I suppose that it's a method judging by the error message.
You should use your parameter object Created
there instead.
回答2:
You can simplify your code:
mySQLCommand.CommandText = "INSERT into table (Created) VALUES (@Created)";
mySQLCommand.Parameters.AddWithValue("Created", DateTime.Now);
mySQLCommand.ExecuteNonQuery();
I believe this will also fix your issue as it is not clear what vetCreated is in your code.
[Update]
Not sure how you handle connection and command as your code doesn't show it. Here is the full code to insert row into a table:
using (var connection = new SqlConnection("your connection string"))
using (var command = connection.CreateCommand())
{
command.CommandText = "INSERT into table (Created) VALUES (@Created)";
command.Parameters.AddWithValue("Created", DateTime.Now);
connection.Open();
command.ExecuteNonQuery();
}
来源:https://stackoverflow.com/questions/6090577/c-sharp-datetime-misunderstanding