2013-09-26 46 views
-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 
+1

歡迎來到StackOverflow:如果你發佈代碼,XML或數據樣本,請**在文本編輯器中突出顯示這些行,然後單擊「代碼示例」按鈕(「 }')在編輯器工具欄上進行恰當的格式化和語法突出顯示! –

+1

什麼行引發異常? – Ovidiu

+0

plz告訴我我錯在哪裏 – user2655643

回答

0

使用SqlDataReader喜歡this example from MSDN並且總是讀完後關閉它。另外,如果數據庫中的「投票」字段是整數,則不需要將其轉換爲字符串。

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

在你的代碼,while dr.HasRows將永遠是真實的,所以它會試圖讀取下一行,即使是沒有的。

作爲便箋,請閱讀this article about debugging in Visual Studio。它有很多很酷的提示。

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() 
+0

非常感謝你這麼多朋友,我得到了一個答案 – user2655643

+1

@ user2655643 ..如果這有助於你,請隨時在downvote標誌下面打一個綠色的勾號.. :) .. – matzone

相關問題