lundi 20 avril 2015

Error when saving datetime to SQL database

im doing a bit of C# winforms coding in my spare time, just getting to grips with everything. I have a SQL script which creates a local db on vs2012 as follows:

-- Creating table 'Users'--
CREATE TABLE [dbo].[Users] (
    [UserID] int IDENTITY(1,1) NOT NULL,
    [Surname] nvarchar(30)  NOT NULL,
    [Forename] nvarchar(30)  NOT NULL,
    [Company] nvarchar (30) NOT NULL,
    [SecurityLevel] int NOT NULL,
    [IssueDate] DateTime  NOT NULL,
    [ExpiryDate] DateTime  NOT NULL,
    [CardID] int NOT NULL,
);
GO

now i want to save details to that table, so i created a method below

  private void btnSaveDetails_Click(object sender, EventArgs e)
    {
        SqlConnection sc = new SqlConnection();
        SqlCommand com = new SqlCommand();
        sc.ConnectionString = (Properties.Settings.Default.BioEngineering);
        sc.Open();
        com.Connection = sc;
        com.CommandText = ("INSERT INTO Users (Forename, Surname, Company, SecurityLevel, IssueDate, ExpiryDate, CardID) VALUES ('" + this.txtFirstName.Text + "','" + this.txtLastName.Text + "','" + this.txtCompany.Text + "','" + this.cboSecurityLevel.Text + "','" + this.dtpIssueDate.Value + "','" + this.dtpExpiryDate.Value + "','" + this.cboCardID.Text + "');");

        com.ExecuteNonQuery();
        sc.Close();
    }

when i run the code i get an error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

i know it has something to do with the datetime format of either the SQL or C# equivalent but i don't know how to format the datetime in order to comply to the error. Any ideas? i tried formatting it withing the Command Text line but it didnt seem to resolve the issue.

Aucun commentaire:

Enregistrer un commentaire