如何避免 IndexOutOfRangeException 索引 DataReader 列?
我在“IndexOutOfRangeException”方面遇到了一些麻烦。我认为这是因为当代码尝试从数据库获取 DateModified col 时,它有时包含 NULL(用户自创建页面以来并不总是更新页面)。
这是我的代码;
s = ("select datemodified, maintainedby, email, hitcount from updates where id = @footid")
Dim x As New SqlCommand(s, c)
x.Parameters.Add("@footid", SqlDbType.Int)
x.Parameters("@footid").Value = footid
c.Open()
Dim r As SqlDataReader = x.ExecuteReader
While r.Read
If r.HasRows Then
datemodified = (r("DateModified"))
maintainedby = (r("maintainedby"))
email = (r("email"))
hitcount = (r("hitcount"))
End If
End While
c.Close()
我认为(在读了一些msdn之后)添加了;
If r.HasRows Then
End If
可以解决问题,但到目前为止添加后我仍然得到相同的旧 IndexOutOfRangeException
(ps,我已尝试将 datemodified 作为字符串/日期时间)
I am having a little trouble with an 'IndexOutOfRangeException'. I think it is because when the code tries to get the DateModified col from the database it sometimes contains NULLS (the users haven't always updated the page since they created it).
Here is my code;
s = ("select datemodified, maintainedby, email, hitcount from updates where id = @footid")
Dim x As New SqlCommand(s, c)
x.Parameters.Add("@footid", SqlDbType.Int)
x.Parameters("@footid").Value = footid
c.Open()
Dim r As SqlDataReader = x.ExecuteReader
While r.Read
If r.HasRows Then
datemodified = (r("DateModified"))
maintainedby = (r("maintainedby"))
email = (r("email"))
hitcount = (r("hitcount"))
End If
End While
c.Close()
I thought (after a bit of msdn) that adding;
If r.HasRows Then
End If
Would solve the problem, but so far after adding I am still getting the same old IndexOutOfRangeException
(ps, I have tried datemodified as string / datetime)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试
r.IsDBNull(columnIndex)
。Try
r.IsDBNull(columnIndex)
.改变
有
作用吗?
Does changing
to
work?
我试图通过传入空值、空集来重新创建您的问题。我无法在您提供的代码示例中重新创建它。您介意发布更多代码,甚至整个页面吗?是否有发生错误的行号?我想进一步挖掘。
I have tried to recreate you issue by passing in nulls, empty sets. I can't recreate it in the sample of code you provided. Would you mind posting more code, maye even the whole page? Is there a line number that the error happens on? I would like to dig in further.