c# - 指定的类型转换无效?

标签 c# asp.net

我在 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>

这是我的错误:

This is my error

它在上面代码的这一行抛出异常:

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/

相关文章:

c# - 在 Unity.MVC4 或 Unity(3.0) 中找不到 PerRequestLifetimeManager 类

c# - 模型绑定(bind)绑定(bind)我的 json 数组,但不绑定(bind)值

asp.net - MySQL 和 ASP.NET (vb) 出现 TIME 自动添加到 DATE 字段的问题

asp.net - 类型 '_Default' 已经定义了一个名为 'Page_Load' 的成员,具有相同的参数类型

C# 构造函数有 2 个参数,但声称它没有带两个参数的构造函数

c# - 高级安装程序 MSI - 程序包只能从 Bootstrap 运行

c# - 如何编写一个将字符串列表作为参数的函数

c# - 为什么 IDependencyResolver 与 System.Web 紧密耦合?

c# - 为什么 CLR 不处理清理代码?

c# - 静态类与。具有私有(private)构造函数和所有静态属性和方法的类?