Invalid attempt to call FieldCount when reader is closed

余生长醉 提交于 2019-11-29 12:34:15

Your code, as displayed is fine. I've taken it into a test project, and it works. It's not immediately clear why you get this message with the code shown above. Here are some debugging tips/suggestions. I hope they're valuable for you.

  • Create a breakpoint on the while (dataReader.Read()). Before it enters its codeblock, enter this in your Immediate or Watch Window: dataReader.HasRows. That should evaluate to true.

  • While stopped on that Read(), open your Locals window to inspect all the properties of dataReader. Ensure that the FieldCount is what you expect from your SELECT statement.

  • When stepping into this Read() iteration, does a student object get created at all? What's the value of dataReader["StructureID"] and all others in the Immediate Window?

It's not the CommandBehavior.CloseConnection causing the problem. That simply tells the connection to also close itself when you close the datareader.

When you use the Using in C#, after the last } from the using, the Connection automatically close, thats why you get the fieldcount to be closed when u try to read him, as that is impossible, because u want those datas, read then before close the using, or u can open and close manually the connection, by not using the (using)

When I got that error, it happened to be a command timeout problem (I was reading some large binary data). As a first attempt, I increased the command timeout (not the connection timeout!) and the problem was solved. Note: while attempting to find out the problem, I tried to listen to the (Sql)connection's StateChanged event, but it turned out that the connection never fall in a "broken" state.

Same problem here. Tested all the above solutions

  • increase command timeout
  • close the connection after read

Here's the code

    1 objCmd.Connection.Open()
    2 objCmd.CommandTimeout = 3000
    3 Dim objReader As OleDbDataReader = objCmd.ExecuteReader()
    4 repeater.DataSource = objReader
    5 CType(repeater, Control).DataBind()
    6 objReader.Close()
    7 objCmd.Connection.Dispose()

Moreover, at line 4 objReader has Closed = False

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!