Click here to Skip to main content
15,891,777 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello my friends,
I have this code
C#
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
        {
            myda = new SqlDataAdapter("Select * from News where NewsDate='" +  Calendar1.SelectedDate.ToString() + "'", mycn);
            dsSelDate = new DataSet();
            myda.Fill(dsSelDate, "AllTables");
            if (dsSelDate.Tables[0].Rows.Count == 0)
            {
                DataGrid1.Visible = false;
            }
            else
            {
                DataGrid1.Visible = true;
                DataGrid1.DataSource = dsSelDate;
                DataGrid1.DataBind();
            }
        }


when I run this code give me the following error

Conversion failed when converting datetime from character string.
any body help !!
Posted

Simple: Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
C#
myda = new SqlDataAdapter("Select * from News where NewsDate=@DT", mycn);
myda.SelectCommand.Parameters.AddWithValue("@DT", Calendar1.SelectedDate);
dsSelDate = new DataSet();
myda.Fill(dsSelDate, "AllTables");
 
Share this answer
 
Hi,

By Default SQL Server will follow MM/DD/yyyy so first check what is your Controls date format.

Now you can change the format of date in SQL Server by DATEFORMAT[^]


Tip :

Always use date format as DD-MMM-yyyy (e.g 04-Sep-2014)

Thanks
Suvabrata
 
Share this answer
 

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