-2

我不确定发生了什么。这段代码昨天运行良好,但今天当我尝试运行它时,我在标记的位置收到“指定的强制转换无效”错误。该查询返回介于 1 和 25 之间的整数。在 Access 数据库中,该字段的数据类型为“数字”,字段大小 =“长整数”。

有关如何纠正此问题的任何线索?

 static void PopulateClientList()
    {
        Console.WriteLine("Populating Client List...");
        Console.WriteLine("\r");
        OleDbConnection conn = new OleDbConnection(strAccessConnABS);
        string query = "SELECT DISTINCT Client FROM ORDERS WHERE Status = 'On Hold';"; 
        OleDbCommand command = new OleDbCommand(query, conn);

        conn.Open();
        OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
        //OleDbDataReader reader = command.ExecuteReader();
        DataTable dt = new DataTable();
        try
        {

            //if (reader.HasRows)
            //{
              //  while (reader.Read())
               // {
                    //clientlist.Add(reader.GetInt32(0)); //cast not valid error happens here
                //}
           // }

             adapter.Fill(dt);

            if (dt.Rows.Count >= 1)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i][0].ToString() != "")
                    clientlist.Add((int)dt.Rows[i][0]);
                }
            }
        }
        catch (OleDbException ex)
        {
        }
        finally
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
        }

    }
4

3 回答 3

1

您的问题可能是超过最大值的值Int32可能已添加到您的表中。在此之前,您的代码不会引发异常。

该字段的数据类型为“数字”,字段大小=“长整数”。

那你为什么要在这里阅读它Int32?:

clientlist.Add(reader.GetInt32(0)); //cast not valid error happens here

将其更改为:

clientlist.Add(reader.GetInt64(0)); 

根据具体clientlist情况,您还必须将其类型更改为接受Int64s。

于 2013-09-25T15:01:05.057 回答
0

在 Access 数据库中,该字段的数据类型为“数字”,字段大小 =“长整数”。

你没有使用很长的:

clientlist.Add(reader.GetInt32(0)); //cast not valid error happens here -> Use GetInt64

我想有人将数据库字段从 int > long 更改了?

于 2013-09-25T15:02:02.837 回答
0

我刚刚注意到了这个问题。不知道它是怎么发生的。当我运行查询时,在数据库内部,第一行是空白的。当读者阅读并尝试将其添加到列表中时,它不会这样做,因为它是一个空值。

于 2013-09-25T15:16:57.240 回答