1

I am having a problem in fetching data into variable in c# from SQL Server.

Here is my code.

SqlConnection myCon = new SqlConnection(@"Data Source=BROWN-PC\KAZIM;Initial Catalog=Agency;Integrated Security=True");

string lastlogt;
string lastlogd;

myCon.Open();

SqlCommand cd2 = new SqlCommand(" SELECT TOP 1 * From (select Top 2 * from Agency.dbo.lastlogindt ORDER BY uid DESC) x ORDER BY uid",myCon);

SqlDataReader sdr;
sdr = cd2.ExecuteReader();
while (sdr.Read()) {
    lastlogd = sdr.GetString(2);
    lastlogt = sdr.GetString(3);

}

myCon.Close();
Dates.Text = lastlogd;
timing.Text = lastlogt;

Now the problem is that the columns of SQL Server from which I'm taking data is of date and time datatypes. and the error I am facing is

Unable to cast object of type 'System.DateTime' to type 'System.String'.

1 Answer 1

3

You need to use GetDateTime and GetTimeSpan methods:

while (sdr.Read()) 
{
     lastlogd = sdr.GetDateTime(2);
     lastlogt = sdr.GetTimeSpan(3);
}

There are other methods for various data types: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx

Sign up to request clarification or add additional context in comments.

2 Comments

Cannot implicitly convert type 'System.Datetime' to 'string' .
Thanks a lot. it's working now. lastlogd = sdr.GetDateTime(2).ToShortDateString(); lastlogt = sdr.GetTimeSpan(3).ToString(); I just wanted to know if I could change the time format from 24 to 12 hour.?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.