我在 ASP.net 中创建了一个表,我想在页面加载后用数据库中的信息填充该表。我收到一个错误,指出指定的转换无效。我究竟做错了什么?这是我的代码
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>
这是我的错误:
它在上面代码的这一行抛出异常:
DateTime Date = reader.GetDateTime(0);
最佳答案
来自您的评论:
this line
DateTime Date = reader.GetDateTime(0);
was throwing the exception
第一列不是有效的日期时间。最有可能的是,您的表中有多个列,并且您正在通过运行以下查询检索它们全部:
SELECT * from INFO
将其替换为检索仅您感兴趣的两列的查询:
SELECT YOUR_DATE_COLUMN, YOUR_TIME_COLUMN from INFO
然后尝试再次读取值:
var Date = reader.GetDateTime(0);
var Time = reader.GetTimeSpan(1); // equivalent to time(7) from your database
或者:
var Date = Convert.ToDateTime(reader["YOUR_DATE_COLUMN"]);
var Time = (TimeSpan)reader["YOUR_TIME_COLUMN"];
关于c# - 指定的类型转换无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27699781/