-1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim n As Integer = 0      
    str = "select vote from CANDIDATEDETAILS where PARTY='Red'"     
    cmd = New SqlCommand(str, con)       
    con.Open()     
    dr = cmd.ExecuteReader() 

    While dr.HasRows      
        dr.Read()      
        n = dr("vote").ToString()    
        n = n + 1
    End While  

    str = "update CANDIDATEDETAILS set vote='" + n.ToString() + "' where PARTY='Rose'"     
    cmd = New SqlCommand(str, con)     
    cmd.ExecuteNonQuery()      
    MsgBox("insert sucessfully")      
    cmd.Dispose()      
    con.Close()

    Label8.Text = n.ToString()
End Sub
4

2 回答 2

1

什么时候没有数据?.. 尝试这个 ..

If dr.HasRows
    While dr.HasRows      
        dr.Read()      
        n = dr("vote").ToString()    
        n = n + 1
    End While  

    str = "update CANDIDATEDETAILS set vote='" + n.ToString() + "' where PARTY='Rose'"     
    cmd = New SqlCommand(str, con)     
    cmd.ExecuteNonQuery()      
    MsgBox("insert sucessfully")      
    cmd.Dispose()
End If      
con.Close()
于 2013-09-26T08:26:54.937 回答
0

像MSDN中的这个示例一样使用 SqlDataReader,并在完成阅读后始终将其关闭。此外,如果数据库中的“投票”字段是整数,则无需将其转换为字符串。

While dr.Read()
    n = dr("vote")
    n = n + 1
End While    
dr.Close()

在您的代码中,while dr.HasRows将始终为真,因此它会尝试读取下一行,即使没有。

作为旁注,请阅读这篇关于在 Visual Studio 中进行调试的文章。它有很多很酷的技巧。

于 2013-09-26T08:20:16.690 回答