Note that there are some explanatory texts on larger screens.

plurals
  1. POCorrect Casting and Conversion for C# (or, Schrödinger's Data Type)
    primarykey
    data
    text
    <p>This may be a basic C# question, but I'm comming from a C/C++ background.</p> <p>I have an application I'm writing that takes a single date value from a Sql Server database. The problem I'm having is that when the database reads the data via the sqlcommand reader, I get an error stating:</p> <blockquote> <p>"Unable to cast object of type 'System.DateTime' to type 'System.String'"</p> </blockquote> <p>Oddly enough, GetString(0) seems to be returning a DateTime during runtime.</p> <p>However, I'm not able to cast the expression as a DateTime, as far as I know. How can I get the DateTime object out of the expression, or convert this expression to a c# string? Here is my code:</p> <pre><code>static public string GetSqlString(string SQLText) { string result = ""; SqlDataReader reader; SqlConnection connection = new SqlConnection("Data Source=DEVDB\\SQLEXPRESS;" + "Initial Catalog=TestDB;" + "Trusted_Connection=Yes;"); using (connection) { SqlCommand sqlcommand = connection.CreateCommand(); sqlcommand.CommandText = SQLText; connection.Open(); reader = sqlcommand.ExecuteReader(); if (reader != null) if (reader.Read()) { // Code breaks on this Line result = reader.GetString(0); ////////////////////////////////////////////////////// // This doesn't seem to work either: result = (DateTime)(reader.GetString(0)).ToShortDateString; // Visual Studio states that this reader.GetString is a string, // oddly enough... } else { // Purposely Bogus Value result = "01/01/1920"; } connection.Close(); } return result; } static public DateTime GetCurrentDateDB() { string dateString; dateString = GetSqlString("SELECT [ViewingDate] FROM [TestDB].[dbo].[AppGlobals] as varchar"); DateTime ComputedDate = DateTime.Parse(dateString); return ComputedDate; } </code></pre> <p>The results of my query, from SQL Server Managment Studio:</p> <blockquote> <p>ViewingDate<br> 2010-05-17 00:00:00.000</p> </blockquote>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload