Click here to Skip to main content
15,891,763 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i have the following error in the code. please help me solve it

Server Error in '/Project' Application.
--------------------------------------------------------------------------------

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

Source Error:


Line 35:
Line 36: DataSet ds = new DataSet();
Line 37: da.Fill(ds);
Line 38: GridView1.DataSource = ds;
Line 39: GridView1.DataBind();

Source File: c:\Users\Shoaib\Desktop\Project\Admin.aspx.cs Line: 37

And the code is as given below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

public partial class Admin : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.Visible = true;
    }
    string connStr = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
        TextBox1.Text = Calendar1.SelectedDate.ToShortDateString();
        Calendar1.Visible = false;
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        Calendar1.Visible = true;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {

        SqlConnection con = new SqlConnection(connStr);
        SqlDataAdapter da = new SqlDataAdapter("select UserName, LoginTime, LogoutTime, Upload UploadFile, Download DownloadFile  from logindata where ltrim(rtrim(str(month(logintime))))+ '/' + ltrim(rtrim(str(day(logintime)))) + '/' + ltrim(rtrim(str(year(logintime)))) ='" + TextBox1.Text + "'", con);
        //+   "+ Convert.ToDateTime;.Convert.ToDateTime (TextBox1.Text), con);
        //Where Logintime='"+TextBox1.Text+"'", con);

        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
        GridView1.Visible = true;
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {

        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataBind();
        GridView1.Visible = true;

    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}
Posted

I suggest changing your to something like the following to use the DATEDIFF SQL function. If the difference between the two days is zero, they are the same date.

... from logindata where DATEDIFF(day,logintime,CAST('" + textbox1.text + "' As SmallDateTime)=0;",con);


If you haven't done so already, you need to add some code to validate that textbox1.text contains a valid date. I usually use CDATE() within a Try Catch block to see if a date is a valid date.

That said, I strongly suggest that you change your SQL Select statement to a parameterized query instead of using a concatenated string. Using a concatenated string, as you did, leaves you program vulnerable to an SQL Injection attack. Also, there is a performance benefit if you use parameterized queries. See this article Use SQL Parameters to Overcome Ad Hoc Performance Issues[^]
 
Share this answer
 
v2
I think it may be due to how your trying to cut up the logintime as a string when that isn't really needed as long as it is a true DateTime() in the database.

Instead get your TextBox1.Text as a DateTime value then compare the too.

So you would need to convert the TextBox1.Text into a DateTime

C#
DateTime dtlogindatetime = TextBox1.Text;

or
C#
DateTime dtlogindatetime;
if (Datetime.Tryparse(TextBox1.Text, out dtlogindatetime)
    //success able to run sql code
else
    //give message that datetime not entered

Then you can update the sql command as follows:

SQL
SqlDataAdapter da = new SqlDataAdapter("select UserName, LoginTime, LogoutTime, Upload UploadFile, Download DownloadFile from logindata where LoginTime = TextBox1.Text + "'", con);



Hope that helps.
 
Share this answer
 
Comments
shoaib_ferrari 23-Jan-13 9:01am    
I have declared LoginTime and LogoutTime under LoginData as Varchar(30)...
M.Edmison 30-Jan-13 9:24am    
I see you have that corrected, but using a DateTime field type might be something to loog into as you can break your dates and times up a little easier. Just a thought.
I added ISNULL to check for a NULL value logintime in the database.

select [UserName], [LoginTime], [LogoutTime], [Upload] as 'UploadFile', [Download] as 'DownloadFile' from logindata where DateDiff(d, Cast(ISNULL([logintime],'01-JAN-1901') as datetime),'" + YourDate.ToString("dd-MMM-yyyy") + "')=0

'
'
' Use this query to find any rows with an invalid "logindate" date. If any rows with invalid "logindate" exist, that is the cause of the error.
select [UserName], [LoginTime], [LogoutTime], [Upload] as 'UploadFile', [Download] as 'DownloadFile',logindate from logindata where Not IsDate(logintime)
 
Share this answer
 
Thanks to Mr. Subrata and Mr. Mike for their precious time and helping me out..I was finally able to solve the error ater 8Hrs with the help of Mr. Subrata guiding me to change the date format in the database...
 
Share this answer
 
C#
//befor convert you must verify the input or use try catch block
datetime YourDate=Convert.ToDate(TextBox1.Text)

System.Data.SqlClient.SqlDataAdapter da = new SqlDataAdapter("select UserName, LoginTime, LogoutTime, Upload UploadFile, Download DownloadFile  from logindata where month(logintime)=" + YourDate.Month + " And day(logintime)=" + YourDate.Day + " and year(logintime)=" + YourDate.Year, con);
 
Share this answer
 
v2
Comments
shoaib_ferrari 23-Jan-13 8:59am    
It says this error now after implementing the changes as suggested by you:
Incorrect syntax near 'year'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near 'year'.

Source Error:


Line 43:
Line 44: DataSet ds = new DataSet();
Line 45: da.Fill(ds);
Line 46: GridView1.DataSource = ds;
Line 47: GridView1.DataBind();
Subrata.In 23-Jan-13 10:21am    
Sorry for my mistake there will be and before year. I modified the solution.
shoaib_ferrari 23-Jan-13 10:34am    
Thank you for your help. But even after modifying it gives the same error as before. i.e.
Exception Details: System.Data.SqlClient.SqlException: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

Subrata.In 23-Jan-13 10:43am    
What is the data type of logintime? Try to change datatype as datetime. If not possible have to convert data type as datetime using cast(logintime as datetime).

Code will be:
SqlDataAdapter da = new SqlDataAdapter("select UserName, LoginTime, LogoutTime, Upload UploadFile, Download DownloadFile from logindata where month(cast(logintime as datetime))=" + YourDate.Month + " And day(cast(logintime as datetime))=" + YourDate.Day + " and year(cast(logintime as datetime))=" + YourDate.Year, con);
shoaib_ferrari 23-Jan-13 10:44am    
Varchar(30)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900