SqlDateTime Overflow, Must be between Error

Introduction

Hi All, I hope you are fine. We all are using SQL parameter in our application right?Yeah it is a good way to restrict the Injections are hijacks. But still if you pass those parameters in the right way, you will face lots of problems. In this article I am going to share you such an Issue. I hope you will like it.

Background

Morning I was working in a grid control which editable, and I selected a row to edit and started editing. In a date field I edited the date and clicked update button. I was expecting an output result as “Successfully updated”. But it didn’t happen. Instead it throws an error. “SqlDateTime Overflow, Must be between”

Using the code

To resolve this issue, first you must understand the root cause for this. I was passing the parameters as follows.

[csharp]
SqlParameter[] myParam = new SqlParameter[3];
myParam[0] = new SqlParameter("@name", myObject.name);
myParam[1] = new SqlParameter("@ValidFrom", myObject.hjcValidFrom);
myParam[2] = new SqlParameter("@ValidTo", myObject.hjcValidTo);
[/csharp]

When I run my application with above code, I got the following error.

So what is the fix/solution?

I changed the parameter as follows.

[csharp]
SqlParameter[] myParam = new SqlParameter[3];
myParam[0] = new SqlParameter("@name", myObject.name);
myParam[1] = new SqlParameter("@ValidFrom", myObject.hjcValidFrom.ToString("MM/dd/YYYY"));
myParam[2] = new SqlParameter("@ValidTo", myObject.hjcValidTo.ToString("MM/dd/YYYY"));
[/csharp]

That solved the issue. Simple right?

Some other case

There are dome other cases you may get this error if you use the codes as follows.
[csharp]
SqlParameter[] myParam = new SqlParameter[3];
DateTime myDate=new DateTime();
myParam[0] = new SqlParameter("@name", myObject.name);
myParam[1] = new SqlParameter("@ValidFrom", myDate);
myParam[2] = new SqlParameter("@ValidTo", myDate);
[/csharp]

What you have to do all to fix this issue is just take the now property value from your date time object and pass it your parameter.

[csharp]
SqlParameter[] myParam = new SqlParameter[3];
DateTime myDate = DateTime.Now;
myParam[0] = new SqlParameter("@name", myObject.name);
myParam[1] = new SqlParameter("@ValidFrom", myDate);
myParam[2] = new SqlParameter("@ValidTo", myDate);
[/csharp]

Conclusion

I hope you enjoyed reading and found this useful. Please share me your valuable feedback. For me it matters a lot.

Kindest Regards
Sibeesh Venu

Leave a Reply

Your email address will not be published. Required fields are marked *

Serverless 360