Click here to Skip to main content
15,885,951 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I want to retrieve previous date from database in datetime control.

what I tried is
C#
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
Updated 25-Aug-14 1:01am
v2
Comments
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.

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:
C#
if(dr.Read())
{
    this.dtpBlockStartDate.Value = (DateTime)dr["Startdate"]; 
}
 
Share this answer
 
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:
C#
var sqlConnection= new SqlConnection(sqlConnectionString);
sqlConnection.Open()

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 :-)
http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/[^]
 
Share this answer
 
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.
C#
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 :-)
 
Share this answer
 
v2

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