指定的转换是无效的? [英] Specified cast is not valid?
问题描述
我在ASP.net创建一个表,我想一旦页面已经加载与数据库中的信息来填充表。我发现了一个错误指定的转换无效。我究竟做错了什么?我的继承人code
公共字符串的getData()
{
字符串htmlStr =; 康涅狄格州的SqlConnection =新的SqlConnection(CONNSTRING);
的SqlCommand命令= conn.CreateCommand();
command.CommandText =SELECT * FROM INFO;
conn.Open();
SqlDataReader的读者= Command.ExecuteReader却(); 而(reader.Read())
{
日期时间日期= reader.GetDateTime(0);
日期时间时间= reader.GetDateTime(1);
htmlStr + =&所述; TR>&下; TD>中+日期+< / TD>< TD>中+时间+< / TD>< / TR>中;
} conn.Close(); 返回htmlStr;
}
<表样式=宽度:100%>
<标题>信息与LT; /字幕>
&所述; TR>
&所述; TD>日期和LT; / TD>
&所述; TD>时间和LT; / TD>
< / TR>
<%=的getData()%GT;
< /表>
这是我的错误:
这是从上面code抛出异常这一行:
日期时间日期= reader.GetDateTime(0);
从您的评论:
这行
日期时间日期= reader.GetDateTime(0);
已抛出异常。
块引用>的第一列是不是有效的日期时间。最有可能的,你有多个列在表中,而你通过运行此查询检索他们的所有的:
SELECT * FROM信息
与检索查询的只有的两列你感兴趣的替换:
SELECT YOUR_DATE_COLUMN,YOUR_TIME_COLUMN从信息
然后重新尝试读取值:
VAR日期= reader.GetDateTime(0);
无功时间= reader.GetTimeSpan(1); //等同于你的数据库的时间(7)或者
VAR日期= Convert.ToDateTime(读卡器[YOUR_DATE_COLUMN]);
VAR时间=(时间跨度)阅读器[YOUR_TIME_COLUMN];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 exceptionThe 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"];
这篇关于指定的转换是无效的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!