Question

I have this function ExecuteSqlParameterizedQuery and here under is my query:

Queryobj.ExecuteSqlParameterizedQuery(String.Format("INSERT INTO tbladd(ID,MyDateTime,Birthday)values({0},@dta, @dtb)", m_Id, MyDateTime.ToString(), MyBirthday.ToString());
  1. MyDateTime is of DateTime datatype.
  2. MyBirthday is of DateTime datatype.

Here is my function:

readonly SqlConnection con = new SqlConnection(PC_Software.Properties.Settings.Default.DbConnectionString);

    public void ExecuteSqlParameterizedQuery(string SQL, string measdt, string dob)
    {
        try
        {
            using (var cmd = new SqlCommand())
            {
                con.Open();
                cmd.Connection = con;
                cmd.Parameters.Clear();  
                cmd.Parameters.AddWithValue("@dta", measdt);
                if(dob != "0DATA#")
                {
                    cmd.Parameters.AddWithValue("@dtb", dob);
                }
                cmd.CommandText = SQL;
                cmd.ExecuteNonQuery();
            }
            con.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

This shows me this particular error: the conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value. the statement has been terminated.

I tried to find the issue but unable to understand how exactly i can do changes to my code to rectify the issue.

Edit:

Also i have this as my Datetime interface:

public interface enn
{
    DateTime MyDateTime
    {
        get;
        set;
    }
}

And datetime declaration is like this:

    DateTime? MyBirthday
    {
        get;
        set;
    }
Was it helpful?

Solution

When you pass the MyBirthday parameter to the method you are converting it to a string:

MyBirthday.ToString()

You should leave it as a DateTime - and the same with MyDateTime

you will obviously need to change your method signature to accept these values

OTHER TIPS

Try using:

MyDateTime.Date

MyBirthday.Date

Queryobj.ExecuteSqlParameterizedQuery(String.Format("INSERT INTO tbladd(ID,MyDateTime,Birthday)values({0},@dta, @dtb)", m_Id, MyDateTime.Date, MyBirthday.Date);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top