I have a table created in ASP.net and I want to populate the table with information from the database once the page has been loaded. I'm getting an error that the specified cast is not valid. What am I doing wrong? Heres my code
public string getData()
{
string htmlStr = "";
SqlConnection conn = new SqlConnection(connString);
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT * from INFO";
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
DateTime Date = reader.GetDateTime(0);
DateTime Time = reader.GetDateTime(1);
htmlStr += "<tr><td>" + Date + "</td><td>" + Time + "</td></tr>";
}
conn.Close();
return htmlStr;
}
<table style="width:100%">
<caption>INFO</caption>
<tr>
<td> Date </td>
<td> Time </td>
</tr>
<%=getData()%>
</table>
This is my error:
It is throwing the exception on this line from the above code:
DateTime Date = reader.GetDateTime(0);
From your comment:
this line
DateTime Date = reader.GetDateTime(0);
was throwing the exception
The first column is not a valid DateTime. Most likely, you have multiple columns in your table, and you're retrieving them all by running this query:
SELECT * from INFO
Replace it with a query that retrieves only the two columns you're interested in:
SELECT YOUR_DATE_COLUMN, YOUR_TIME_COLUMN from INFO
Then try reading the values again:
var Date = reader.GetDateTime(0);
var Time = reader.GetTimeSpan(1); // equivalent to time(7) from your database
Or:
var Date = Convert.ToDateTime(reader["YOUR_DATE_COLUMN"]);
var Time = (TimeSpan)reader["YOUR_TIME_COLUMN"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With