指定演员表无效?

时间:2014-12-30 04:58:23

标签: 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);

3 个答案:

答案 0 :(得分:10)

来自你的评论:

  

此行DateTime Date = reader.GetDateTime(0);抛出异常

第一列不是有效的DateTime。最有可能的是,您的表格中有多列,并且您通过运行此查询来检索它们 all

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"];

答案 1 :(得分:0)

htmlStr是字符串然后您需要DateTime变量到string

while (reader.Read())
                {
                    DateTime Date = reader.GetDateTime(0);
                    DateTime Time = reader.GetDateTime(1);
                    htmlStr += "<tr><td>" + Date.ToString() + "</td><td>"  + 
                    Time.ToString() + "</td></tr>";                  
                }

答案 2 :(得分:0)

尝试一下:

public void LoadData()
        {
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stocks;Integrated Security=True;Pooling=False");
            SqlDataAdapter sda = new SqlDataAdapter("Select * From [Stocks].[dbo].[product]", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            DataGridView1.Rows.Clear();

        foreach (DataRow item in dt.Rows)
        {
            int n = DataGridView1.Rows.Add();
            DataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
            DataGridView1.Rows[n].Cells[1].Value = item["Productname"].ToString();
            DataGridView1.Rows[n].Cells[2].Value = item["qty"].ToString();                
            if ((bool)item["productstatus"])
            {
                DataGridView1.Rows[n].Cells[3].Value = "Active";
            }
            else
            {
                DataGridView1.Rows[n].Cells[3].Value = "Deactive";
            }