Will_G
Will_G

Reputation: 269

error Sql query with datetime

I got a error when I do the follow:

DateFrom has as datatype of datetime

enter image description here

My C# code:

string strQuery = "Select * FROM Agenda Where   DateFrom='" + Calendar1.SelectedDate.Date.Date + "' ";
SqlCommand command = new SqlCommand(strQuery, Global.myConn);
da = new SqlDataAdapter(command);
da.Fill(Global.dsAgenda, "Tabel");
ddlActivity.DataSource = Global.dtAgenda;
ddlActivity.DataBind();

Calendar1 type:

enter image description here

Error:

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

Upvotes: 0

Views: 513

Answers (2)

Carsten
Carsten

Reputation: 11606

You should prefer using parameters:

string strQuery = "SELECT * FROM Agenda WHERE DateFrom = @Date";
SqlCommand command = new SqlCommand(strQuery, Global.myConn);
command.Parameters.Add("@Date", SqlDbType.DateTime).Value = Calendar1.SelectedDate;

Upvotes: 4

Amit
Amit

Reputation: 15387

Use this

 Convert(DateTime,Calendar1.SelectedDate.Date.Date,103)

Upvotes: 1

Related Questions