2012-03-07 27 views
1

你能檢查我的編碼並讓我知道我在做什麼錯嗎?.NextResult()方法確實給出了一個錯誤,指出沒有數據存在

我試圖使用DataReader的.NextResult()方法,但我得到一個錯誤,沒有數據存在。

第一個查詢返回一個值,但第二個查詢是問題。

Dim strSqlStatement As String = "Select Count(*) As TotalRows " & _ 
              "From Parents " & _ 
             "Where (FatherName = @SearchValue " & _ 
             " Or MotherName = @SearchValue);" 

strSqlStatement = strSqlStatement & "Select FatherName, MotherName " & _ 
              "From Parents " & _ 
             "Where (FatherName = @SearchValue " & _ 
             " Or MotherName = @SearchValue)" 

' Set up the sql command and lookup the parent. 
'---------------------------------------------- 
Using objSqlCommand As SqlCommand = New SqlCommand(strSqlStatement, ObjConnection) 

    With objSqlCommand 

     ' Add SqlParameters to the SqlCommand. 
     '------------------------------------- 
     .Parameters.Clear() 
     .Parameters.AddWithValue("@SearchValue", TextBoxParentsName.Text) 

     ' Open the SqlConnection before executing the query. 
     '--------------------------------------------------- 
     Try 
      ObjConnection.Open() 

      ' Execute the query to see if the parents are in the database. 
      '------------------------------------------------------------- 

      ' Display the parent info. 
      '------------------------- 
      Dim reader As SqlDataReader = .ExecuteReader() 

      reader.Read() 

      Dim countOfRows = reader("TotalRows") 

      If countOfRows = 1 Then 

       reader.NextResult() 

       TextBoxParentsName.Text = reader("FatherName").ToString() 
       LabelBothParents.Text = "Father: " & TextBoxParentsName.Text & " Mother: " & reader("MotherName") 
      End If 

     Catch exErrors As Exception 

      MessageBox.Show("Sorry, there was an error. Details follow: " & _ 
            vbCrLf & vbCrLf & exErrors.Message, _ 
            "Error") 

      TextBoxParentsName.Focus() 
     Finally 
      blnDisableParentIdTextChanged = False 

      ObjConnection.Close() 
     End Try 

    End With ' objSqlCommand 
End Using ' objSqlCommand 

回答

1

找到丟失的語句:

我需要添加:

reader.Read()

的reader.NextResult後這方面的編碼:

If countOfRows = 1 Then 

    reader.NextResult() 

    reader.Read() ' This is what I needed to add. 

    TextBoxParentsName.Text = reader("FatherName").ToString() 
    LabelBothParents.Text = "Father: " & TextBoxParentsName.Text & " Mother: " & reader("MotherName") 
End If 

我希望這可以幫助像我一樣卡住的人。

相關問題