Click here to Skip to main content
13,196,126 members (52,509 online)
Rate this:
Please Sign up or sign in to vote.
See more:
I want to retrieve previous date from database in datetime control.

what I tried is
queryString = "SELECT Startdate FROM master WHERE srno="+ t +"";
while (dr.Read())
    DateTime stdate = Convert.ToDateTime(dr.GetValue(2).ToString());
    this.dtpBlockStartDate.Value = new DateTime(stdate.Year , stdate.Month , stdate.Day);

datetime control is displaying current date and not the date from database.
Posted 25-Aug-14 0:56am
Updated 25-Aug-14 1:01am
Neetin_1809 25-Aug-14 7:26am
modify Your QUeryString to TOp 1 clause and Use Order By Clause
sachees123 25-Aug-14 7:38am
getting date is not a problem, but getting it displayed in datetime control is a BIG problem. Also there are many other fields in query.
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

1.The parameter t from your command should be the date that you want, if you want yesterday should be:
DateTime t = DateTime.Now.AddDays(-1);

2.Then you should refine your reading code like this:
    this.dtpBlockStartDate.Value = (DateTime)dr["Startdate"]; 
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

When you are working with date and time objects. Then do not convert it to a string.
Only convert to a string when you want to show it to the user.

If table column "Startdate" is a datetime type in MS SQL. You can use the value direct like:
var sqlConnection= new SqlConnection(sqlConnectionString);
var sqlCommand = sqlConnection.CreateCommand();
sqlCommand.CommandText = "SELECT Startdate FROM master WHERE srno=@srno";
sqlCommand.Parameters.AddWithValue("srno", t);
object result = sqlCommand.ExecuteScalar();
if (result != null)
  dtpBlockStartDate.Value = (DateTime)result;

Remember to use parameterized sql statement :-)[^]
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

Hello ,
If you DataType is DateTime & Using with C#.Try the Following Code to set a value.
There is a CustomFormat Property for the DatePicker control that is needed to be specified.
dtpBlockStartDate.CustomFormat = "dd-MMM-yyyy";
dtpBlockStartDate.Value =Convert.ToDateTime(ds.Tables[0].Rows[0][0]);

ds refers to dataset & i am suposing that it is in first column.

Try To debug it .SomeWhere you might be resetting it to Currrent Date.

If any Problem Then Paste Your Complete Code
Hope It Helps You
Happy coding :-)

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web01 | 2.8.171019.1 | Last Updated 28 Aug 2014
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100